问题原文
原帖链接 · Marcos Sander · CC BY-SA 4.0
I have an array which gets filled with different error messages as my script runs.
I need a way to check if it is empty of not at the end of the script and take a specific action if it is.
I have already tried treating it like a normal VAR and using -z to check it, but that does not seem to work. Is there a way to check if an array is empty or not in Bash?
社区高分解答
原帖链接 · wget · CC BY-SA 3.0
You can also consider the array as a simple variable. In that way, just using
if [ -z "$array" ]; then
echo "Array empty"
else
echo "Array non empty"
fi
or using the other side
if [ -n "$array" ]; then
echo "Array non empty"
else
echo "Array empty"
fi
The problem with that solution is that if an array is declared like this: array=('' foo). These checks will report the array as empty, while it is clearly not. (thanks @musiphil!)
Using [ -z "$array[@]" ] is clearly not a solution neither. Not specifying curly brackets tries to interpret $array as a string ([@] is in that case a simple literal string) and is therefore always reported as false: "is the literal string [@] empty?" Clearly not.
摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。
