我最近遇到了一个shell脚本,declare -- FOO=""
该脚本显然是typeset -- FOO=""
在非bash shell中拼写的。
为什么我要做到这一点,而不是普通的FOO=""
或export FOO
?
使用的最重要目的declare
是控制范围,或使用其他方式无法访问的数组类型。
举个例子:
print_dashes() { for (( i=0; i<10; i++; do printf '-'; done; echo; }
while read -p "Enter a number: " i; do
print_dashes
echo "You entered: $i"
done
您希望打印出用户输入的号码,对吗?但是,相反,它会始终打印的值i
是print_dashes
叶子它完成时。
请考虑:
print_dashes() {
declare i # ''local i'' would also have the desired effect
for (( i=0; i<10; i++; do printf '-'; done; echo;
}
...现在i
是local,因此新分配的值不会超出其调用范围。
相反,有时您需要声明一个全局变量,并通过意图向代码读者清楚地表明您正在执行此操作,或者同时将某些内容声明为数组(否则declare
将隐式指定全局状态) 。你也能做到:
myfunc() {
declare arg # make arg local
declare -g -A myfunc_args_seen # make myfunc_args_seen a global associative array
for arg; do
myfunc_args_seen["$arg"]=1
done
echo "Across all invocations of myfunc, we have seen the following arguments:"
printf ' - %q\n' "${!myfunc_args_seen[@]}"
}
普通的shell数组只能被分配:my_arr=( one two three )
但是,对于关联数组(键为字符串)则不是这种情况。对于这些,您需要声明它们:
declare -A my_arr=( ["one"]=1 ["two"]=2 ["three"]=3 )
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句