检查 bash 中数组是否为空

问题描述 投票:0回答:1

我想看看 bash 中的数组是否为空

key=[]
key1=["2014"]

我尝试过以下方法:

[[ -z "$key" ]] && echo "empty" || echo "not Empty" 
[[ -z "$key1" ]] && echo "empty" || echo "not Empty"

两者都返回“非空”

[[ $key==[] ]] && echo "empty" || echo "not Empty"
[[ $key1==[] ]] && echo "empty" || echo "not Empty"

两者都返回“空”。

arrays bash if-statement
1个回答
35
投票

正如 @cheapner 在评论中指出的,您没有正确定义数组。

key=()
key1=("2014" "kdjg")

key
这里是一个空数组,
key1
2
元素。

然后打印数组中的元素数量,分别是

0
2

echo "${#key[@]}"
echo "${#key1[@]}"

这分别打印

empty
not empty

if (( ${#key[@]} == 0 )); then
    echo empty
fi

if (( ${#key1[@]} != 0 )); then
    echo not empty
fi
© www.soinside.com 2019 - 2024. All rights reserved.