declare命令是bash的一個(gè)內(nèi)建命令,它可以用來(lái)聲明shell變量,設(shè)置變量的屬性(Declare variables and/or give them attributes)。該命令也可以寫(xiě)作typeset。雖然人們很少使用這個(gè)命令,如果知道了它的一些用法,就會(huì)發(fā)現(xiàn)這個(gè)命令還是挺有用的。
[root@web ~]# type -a declare
declare is a shell builtin
[root@web ~]#
[root@jfht ~]# type -a typeset
typeset is a shell builtin
[root@jfht ~]#
[root@web ~]# x=6/3
[root@web ~]# echo $x
6/3
[root@web ~]# declare -i x
[root@web ~]# echo $x
6/3
[root@web ~]# x=6/3
[root@web ~]# echo $x
2
如果變量被聲明成整數(shù),可以把表達(dá)式直接賦值給它,bash會(huì)對(duì)它求值。
[root@jfht ~]# x=error
[root@jfht ~]# echo $x
0
如果變量被聲明成整數(shù),把一個(gè)結(jié)果不是整數(shù)的表達(dá)式賦值給它時(shí),就會(huì)變成0.
[root@jfht ~]# x=3.14
-bash: 3.14: syntax error: invalid arithmetic operator (error token is ".14")
如果變量被聲明成整數(shù),把一個(gè)小數(shù)(浮點(diǎn)數(shù))賦值給它時(shí),也是不行的。因?yàn)閎ash并不內(nèi)置對(duì)浮點(diǎn)數(shù)的支持。
[root@web ~]#
[root@jfht ~]# declare +i x
此命令的結(jié)果是取消變量x的整數(shù)類(lèi)型屬性。
[root@jfht ~]# x=6/3
[root@jfht ~]# echo $x
6/3
因?yàn)樽兞縳不是整型變量,所以不會(huì)自動(dòng)對(duì)表達(dá)式求值??梢圆捎孟旅鎯蓚€(gè)方式。
[root@jfht ~]# x=$[6/3]
[root@jfht ~]# echo $x
2
[root@jfht ~]# x=$((6/3))
[root@jfht ~]# echo $x
2
[root@jfht ~]#
[root@jfht ~]# declare -r r
[root@jfht ~]# echo $r
[root@jfht ~]# r=xxx
-bash: r: readonly variable
[root@jfht ~]# declare -r r=xxx
-bash: declare: r: readonly variable
[root@jfht ~]# declare +r r
-bash: declare: r: readonly variable
[root@jfht ~]#
[root@jfht ~]# declare +r r
-bash: declare: r: readonly variable
[root@jfht ~]#
[root@jfht ~]# unset r
-bash: unset: r: cannot unset: readonly variable
[root@jfht ~]#
[root@jfht ~]# declare -a names
[root@jfht ~]# names=Jack
[root@jfht ~]# echo ${names[0]}
Jack
[root@jfht ~]# names[1]=Bone
[root@jfht ~]# echo ${names[1]}
Bone
[root@jfht ~]# echo ${names}
Jack
[root@jfht ~]# echo ${names[*]}
Jack Bone
[root@jfht ~]# echo ${#names}
4
直接引用names,相當(dāng)于引用names[0]
[root@jfht ~]# echo ${#names[*]}
2
[root@jfht ~]# echo ${names[@]}
Jack Bone
[root@jfht ~]# echo ${#names[@]}
2
[root@jfht ~]# declare -p names
declare -a names='([0]="Jack" [1]="Bone")'
[root@jfht ~]#
[root@jfht ~]# declare -F
declare -f add_jar
declare -f add_jar2
declare -f add_jar3
[root@jfht ~]# declare -f
add_jar ()
{
[ -e $1 ] && CLASSPATH=$CLASSPATH:$1
}
add_jar2 ()
{
if [ -e $1 ]; then
CLASSPATH=$CLASSPATH:$1;
else
if [ -e $2 ]; then
CLASSPATH=$CLASSPATH:$2;
fi;
fi
}
add_jar3 ()
{
if [ -e $1 ]; then
CLASSPATH=$CLASSPATH:$1;
else
if [ -e $2 ]; then
CLASSPATH=$CLASSPATH:$2;
else
if [ -e $3 ]; then
CLASSPATH=$CLASSPATH:$3;
fi;
fi;
fi
}
[root@jfht ~]# declare -f add_jar
add_jar ()
{
[ -e $1 ] && CLASSPATH=$CLASSPATH:$1
}
[root@jfht ~]# declare -F add_jar
add_jar
[root@jfht ~]# declare -F add_
[root@jfht ~]# declare -F add_*
[root@jfht ~]# declare -F 'add_*'
[root@jfht ~]#
聯(lián)系客服