foc*_*eng 3 bash shell-script associative-array
如何检查字典(关联数组)是否为空?我只是使用declare -A dict. 我想知道它是否刚刚声明但没有任何密钥。
关联数组的长度(或其中的元素数)可用作${#array[@]},就像普通数组一样。如果此数字为零,则数组为空。
if [ "${#array[@]}" -ne 0 ]; then
echo 'array is not empty'
fi
Run Code Online (Sandbox Code Playgroud)
在一个普通的 shell 变量上,可以使用-vtest 来测试它是否存在:
if [ -v variable ]; then
echo 'variable exists'
fi
Run Code Online (Sandbox Code Playgroud)
...但这在数组上并不直观。因此,您不能可靠地使用它来确定数组是否存在但为空,或者是否尚未声明。
如果它们的0键存在,则测试将在数组上为真。