declare 是 shell 的内置命令,它可以用来设置一个变量的值及其属性。它的使用形式是:
declare [-aAfFilrtux] [-p] [name[=value] ...] 如果执行 declare 时不带任何参数,那么它将列出所有的变量值及其属性。
-r 选项可以给变量添加只读属性,如果你尝试修改这个变量,那么将得到一个错误的信息:$ declare -r Vareadonly=only
$ echo $Vareadonly
only
$ Vareadonly=you
bash: Vareadonly: readonly variable
-i 选项使变量后面的赋值视为整型:$ declare -i integer=a
$ echo $integer
0
$ integer=8
$ echo $integer
8 给 integer 变量赋值 a,但 integer 被设置为只接受整型,所以这里无法识别,故为 0 。
-a 选项用来声明一个数组:
[Bash shell] 纯文本查看 复制代码 #!/bin/bash
declare -a array
let i=0
while [ $i -lt 5 ]
do
array[$i]=$i
(( i++ ))
done
echo ${array[@]}
exit 0
运行输出:$ sh declare.sh
0 1 2 3 4 其实像上面不用 declare 声明数组也是可以的,bash 能自己识别数组。${array[@]} 或 ${array} 会遍历整个数组。
-x 选项会将变量 export 出来。
被 export 出来的变量在运行的脚本的所有的子进程中都可用,但是需要注意 export 的变量不会影响父进程(调用这个脚本的 shell 进程)。看下面脚本演示:
[Bash shell] 纯文本查看 复制代码 #!/bin/bash
ARGS=2
E_WRONGARGS=65
if [ $# -ne "$ARGS" ]
then
echo "Usage: `basename $0` filename column-number"
exit $E_WRONGARGS
fi
filename=$1
column_number=$2
export column_number
awkscript='{total += $ENVIRON["column_number"]}
END { print total }'
awk "$awkscript" "$filename"
exit 0
上面脚本用来统计一个文件中一列的数字的和,比如这个文件的内容为:$ cat test.txt
1 3
2 5
11 6
33 56
21 26
12 53 那么使用上面的脚本进行统计:$ ./exp.sh test.txt 1
80
$ ./exp.sh test.txt 2
149 在上面的脚本中注意几点:
1. 一个变量可以保存一个 awk 脚本,这里这个变量是 awkscript 。
2. 将 column_number这个变量 export 出来后,它就可以被后面的脚本使用。
3. ENVIRON 是 awk 的内置环境变量, 使用它可以直接获得环境变量。它是一个字典数组,环境变量名 就是它的键值,如:awk 'BEGIN{print ENVIRON["HOME"]}'
如果将上面的 export 语句屏蔽掉,不论在命令行中指定第 2 个参数(column_number)为多少,总是只能统计第一列的数字和。这是因为,执行 awk 脚本时,需要当前 shell 派生出(fork)出一个子进程来进行执行 awk,如果不用 export 将变量倒出,那么 awk 将会认为$ENVIRON["column_number"] 中的 column_number
的值为 0 。
-u 和 -l 选项分别可以将变量强制声明为大写和小写形式,如:
[Bash shell] 纯文本查看 复制代码 #!/bin/bash
declare -l str1="HELLO"
declare -u str2="world"
echo $str1 $str2
运行输出:
-f 选项会列出之前定义的函数,如:
[Bash shell] 纯文本查看 复制代码 #!/bin/bash
func1()
{
echo "hello world"
}
func2()
{
echo "how are you"
}
declare -f
exit 0
运行输出:$ sh exp4.sh
func1 ()
{
echo "hello world"
}
func2 ()
{
echo "how are you"
}
-F 选项则是只显示函数名,而不会显示函数内容,如:$sh exp4.sh
declare -f func1
declare -f func2 |