【发布时间】:2015-01-11 14:28:43
【问题描述】:
如何测试是否在 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
嗯,这很快。
再次感谢各位。
【问题讨论】: