问题描述
如何测试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
让我们比较一下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测试中是否声明了关联数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!