shell變數以及如何使用變數

2021-09-20 16:58:06 字數 2448 閱讀 3725

shell變數

變數 (記憶體空間)

增加指令碼的靈活性, 適用性 

型別:自定義變數

環境變數(path)

特殊變數

自定義變數 

1  宣告變數

# 變數名稱=變數值

變數名稱規範:

只能由數字、字母、下劃線組成 

不能以數字開頭 

[root@shell ~]# name=tom

2 呼叫變數的值

$變數名稱

$ 變數名稱後緊跟數字, 字元的時候

[root@shell ~]# name=cat

[root@shell ~]# echo "this is a $name"

this is a cat

[root@shell ~]# echo "there are some $s"

there are some cats

shell變數的值預設全都作為字元處理

[root@shell ~]# a=10

[root@shell ~]# b=20

[root@shell ~]# c=a+b

[root@shell ~]# echo $c

a+b[root@shell ~]# c=$a+$b

[root@shell ~]# echo $c

10+20

[root@shell ~]# 

3 如何使用變數的值作數**算 

方法1: $((expression))

[root@shell ~]# a=10

[root@shell ~]# b=20

[root@shell ~]# c=$((a+b))

[root@shell ~]# echo $c

30[root@shell ~]# 

方法2: 關鍵字  let  

[root@shell ~]# a=10

[root@shell ~]# b=20

[root@shell ~]# let c=a+b

[root@shell ~]# echo $c

30[root@shell ~]# 

方法3: 關鍵字  declare 

[root@shell ~]# a=10

[root@shell ~]# b=20

[root@shell ~]# declare -i c=a+b

[root@shell ~]# echo $c

30[root@shell ~]# 

數**算符: +-

*/ 整除

% 取餘

生成10以內的隨機數        echo $random   ------> 生成隨機數

[root@shell ~]# echo $((random%10))

9[root@shell ~]# echo $((random%10))

8[root@shell ~]# echo $((random%10))

4[root@shell ~]# echo $((random%10))

54 命令引用 

反引號 `command`

$(command)

[root@shell ~]# a=`ls -ldh /etc/`

[root@shell ~]# echo $a

drwxr-xr-x. 65 root root 4.0k 11月 20 16:32 /etc/

[root@shell ~]# b=$(ls -ldh /etc/)

[root@shell ~]# echo $b

drwxr-xr-x. 65 root root 4.0k 11月 20 16:32 /etc/

[root@shell ~]# 

5 刪除變數 

# unset 變數名稱

環境變數 

1) 檢視環境變數 

[root@shell ~]# env

hostname=shell.linux.com

term=xterm

shell=/bin/bash

histsize=1000

ssh_client=192.168.122.1 44503 22

ssh_tty=/dev/pts/0

user=root

2) 定義環境變數, 修改環境變數的值

# export 變數名稱=變數值

/etc/profile

/etc/bashrc

3) 特殊變數   $$   -----> shell本身的pid  

$! -----> shell最後執行的後台process的pid 

$0  -----> shell本身的引數個數   

$1~$n  ----> 新增到shell的各引數值。$1是第乙個引數,依次排

$? 代表上一條命令的執行狀態

0---255

0 執行成功

shell變數賦值以及使用

1 變數賦值 定義變數時,變數名不加美元符號,如 name str lili 特別注意 變數名和等號之間不能有空格 其他注意事項與其他語言相通 2 使用變數 使用乙個定義過的變數,只有在變數名前面加美元符號 即可 name str lili echo name str echo 注 變數名外面的花括...

Shell 使用Shell變數

變數是乙個字串,我們分配乙個值。分配的值可以是乙個數字,文字,檔名,裝置,或任何其他型別的資料。變數是沒有超過實際資料的指標。shell,可以建立,分配和刪除變數。變數的名稱可以包含只有字母 a到z或a到z 數字 0 9 或下劃線 按照慣例,unix的shell變數將有自己的名稱以大寫字母。下面的例...

Shell 中的變數以及使用方式

1.常用系統變數 home pwd shell user等 展示如下 root bigdata shell echo home root root bigdata shell echo pwd opt shell root bigdata shell echo shell bin bash root...