declare為shell指令,在第一種文法中可用來聲明變數並設定變數的屬性([rix]即為變數的屬性),在第二種文法中可用來顯示shell函數。若不加上任何參數,則會顯示全部的shell變數與函數(與執行set指令的效果相同)。
文法
declare [+/-][rxi][變數名稱=設定值] 或 declare -f
參數說明:
- +/- "-"可用來指定變數的屬性,"+"則是取消變數所設的屬性。
- -f 僅顯示函數。
- r 將變數設定為唯讀。
- x 指定的變數會成為環境變數,可供shell以外的程式來使用。
- i [設定值]可以是數值,字串或運算式。
執行個體
聲明整數型變數
# declare -i ab //聲明整數型變數
# ab=56 //改變變數內容
# echo $ab //顯示變數內容
56
改變變數屬性
# declare -i ef //聲明整數型變數
# ef=1 //變數賦值(整數值)
# echo $ef //顯示變數內容
1
# ef="wer" //變數賦值(文本值)
# echo $ef
0
# declare +i ef //取消變數屬性
# ef="wer"
# echo $ef
wer
設定變數唯讀
# declare -r ab //設定變數為唯讀
# ab=88 //改變變數內容
-bash: ab: 唯讀變數
# echo $ab //顯示變數內容
56
聲明陣列變數
# declare -a cd='([0]="a" [1]="b" [2]="c")' //聲明陣列變數
# echo ${cd[1]}
b //顯示變數內容
# echo ${cd[@]} //顯示整個陣列變數內容
a b c
顯示函數
# declare -f
command_not_found_handle ()
{
if [ -x /usr/lib/command-not-found ]; then
/usr/bin/python /usr/lib/command-not-found -- $1;
return $?;
else
if [ -x /usr/share/command-not-found ]; then
/usr/bin/python /usr/share/command-not-found -- $1;
return $?;
else
return 127;
fi;
fi
}