Linux declare命令用于聲明 shell 變量。
declare為shell指令,在第一種語法中可用來聲明變量并設(shè)置變量的屬性([rix]即為變量的屬性),在第二種語法中可用來顯示shell函數(shù)。若不加上任何參數(shù),則會(huì)顯示全部的shell變量與函數(shù)(與執(zhí)行set指令的效果相同)。
declare [+/-][rxi][變量名稱=設(shè)置值] 或 declare -f
參數(shù)說明:
聲明整數(shù)型變量
# declare -i ab //聲明整數(shù)型變量 # ab=56 //改變變量內(nèi)容 # echo $ab //顯示變量內(nèi)容 56
改變變量屬性
# declare -i ef //聲明整數(shù)型變量 # ef=1 //變量賦值(整數(shù)值) # echo $ef //顯示變量內(nèi)容 1 # ef="wer" //變量賦值(文本值) # echo $ef 0 # declare +i ef //取消變量屬性 # ef="wer" # echo $ef wer
設(shè)置變量只讀
# declare -r ab //設(shè)置變量為只讀 # ab=88 //改變變量內(nèi)容 -bash: ab: 只讀變量 # echo $ab //顯示變量內(nèi)容 56
聲明數(shù)組變量
# declare -a cd='([0]="a" [1]="b" [2]="c")' //聲明數(shù)組變量
# echo ${cd[1]}
b //顯示變量內(nèi)容
# echo ${cd[@]} //顯示整個(gè)數(shù)組變量內(nèi)容
a b c
顯示函數(shù)
# 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
}