问题描述
如何测试是否在 Bash 中声明了关联数组?我可以测试一个变量,如:
How can I test if an associative array is declared in Bash? I can test for a variable like:
[ -z $FOO ] && echo nope
但我似乎不适用于关联数组:
but I doesn't seem to work for associative arrays:
$ unset FOO
$ declare -A FOO
$ [ -z $FOO ] && echo nope
nope
$ FOO=([1]=foo)
$ [ -z $FOO ] && echo nope
nope
$ echo ${FOO[@]}
foo
感谢您的回答,两者似乎都有效,所以我让速度决定:
Thank you for your answers, both seem to work so I let the speed decide:
$ 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 的解决方案与之前的解决方案:
Let's speed compare Chepner's solution against the previous ones:
#!/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
选项:
In bash
4.2 or later, you can use the -v
option:
[[ -v FOO[@] ]] && echo "FOO set"
注意,在任何版本中,使用
Note that in any version, using
declare -A FOO
实际上并没有立即创建关联数组;它只是在名称 FOO
上设置一个属性,允许您将名称分配为关联数组.数组本身在第一次赋值之前不存在.
doesn't actually create an associative array immediately; it just sets an attribute on the name FOO
which allows you to assign to the name as an associative array. The array itself doesn't exist until the first assignment.
这篇关于在 Bash 中测试是否声明了关联数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!