如何测试 Bash 中是否声明了关联数组?我可以测试一个变量,例如:
[ -z $FOO ] && echo nope
但我似乎对关联数组不起作用:
$ unset FOO
$ declare -A FOO
$ [ -z $FOO ] && echo nope
nope
$ FOO=([1]=foo)
$ [ -z $FOO ] && echo nope
nope
$ echo ${FOO[@]}
foo
编辑:
感谢您的回答,两者似乎都有效,所以我让速度决定:
$ cat test1.sh
#!/bin/bash
for i in {1..100000}; do
size=${#array[@]}
[ "$size" -lt 1 ] && :
done
$ time bash test1.sh #best of five
real 0m1.377s
user 0m1.357s
sys 0m0.020s
和另一个:
$ cat test2.sh
#!/bin/bash
for i in {1..100000}; do
declare -p FOO >/dev/null 2>&1 && :
done
$ time bash test2.sh #again, the best of five
real 0m2.214s
user 0m1.587s
sys 0m0.617s
编辑 2:
让我们快速比较 Chepner 的解决方案与之前的解决方案:
#!/bin/bash
for i in {1..100000}; do
[[ -v FOO[@] ]] && :
done
$ time bash test3.sh #again, the best of five
real 0m0.409s
user 0m0.383s
sys 0m0.023s
嗯,那很快。
再次感谢大家。
最佳答案
在 bash
4.2 或更高版本中,您可以使用 -v
选项:
[[ -v FOO[@] ]] && echo "FOO set"
请注意,在任何版本中,使用
declare -A FOO
实际上并没有立即创建关联数组;它只是在名称 FOO
上设置一个属性,允许您将名称作为关联数组分配给该名称。数组本身在第一次赋值之前不存在。
关于bash - 在 Bash 中测试是否声明了关联数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26925905/