標籤:
1、shell中的變數可以自訂,shell中使用變數時用$
name="shero"
echo "hi ${name}"
[email protected]:/home/shero/shell# ./test2.sh
hi shero
注意,變數名和等號之間不能有空格,這可能和你熟悉的所有程式設計語言都不一樣。同時,變數名的命名須遵循如下規則:
- 首個字元必須為字母(a-z,A-Z)。
- 中間不能有空格,可以使用底線(_)。
- 不能使用標點符號。
- 不能使用bash裡的關鍵字(可用help命令查看保留關鍵字)。
- 推薦給所有變數加上花括弧,這是個好的編程習慣。
- 使用變數的時候才加美元符($)。
- 定義變數時,變數名不加貨幣符號($)
2、刪除變數
unset 變數名
eg:
name="shero"
FirstName="huo"
echo "hi $name $FirstName"
unset name
echo "hi $name $FirstName"
執行結果:
[email protected]:/home/shero/shell# ./test2.sh
hi shero huo
hi huo
3、變數可以被重新定義:
name="shero"
FirstName="huo"
echo "hi $name $FirstName"
#unset name
#echo "hi $name $FirstName"
name="lucy"
echo "hi $name"
執行結果:
[email protected]:/home/shero/shell# ./test2.sh
hi shero huo
hi lucy
4、變數可以設定成唯讀變數
name="shero"
FirstName="huo"
echo "hi $name $FirstName"
#unset name
#echo "hi $name $FirstName"
readonly name
name="lucy"
FirstName="Lee"
echo "hi ${name} ${FirstName}"
執行結果:
[email protected]:/home/shero/shell# ./test2.sh
hi shero huo
./test2.sh: line 7: name: readonly variable
hi shero Lee
變數類型
運行shell時,會同時存在三種變數:
1) 局部變數
局部變數在指令碼或命令中定義,僅在當前shell執行個體中有效,其他shell啟動的程式不能訪問局部變數。
2) 環境變數
所有的程式,包括shell啟動的程式,都能訪問環境變數,有些程式需要環境變數來保證其正常運行。必要的時候shell指令碼也可以定義環境變數。
3) shell變數
shell變數是由shell程式設定的特殊變數。shell變數中有一部分是環境變數,有一部分是局部變數,這些變數保證了shell的正常運行
shell學習筆記(1)-變數