I am trying to see if an array is empty in bash
key=[]
key1=["2014"]
I have tried following ways:
[[ -z "$key" ]] && echo "empty" || echo "not Empty"
[[ -z "$key1" ]] && echo "empty" || echo "not Empty"
Both return 'not Empty'
[[ $key==[] ]] && echo "empty" || echo "not Empty"
[[ $key1==[] ]] && echo "empty" || echo "not Empty"
Both return empty
.
As noted by @cheapner in the comments, you are not defining your arrays correctly.
key=()
key1=("2014" "kdjg")
key
is here an empty array and key1
has 2
elements.
This then prints the number of elements in the arrays, which is 0
and 2
respectively:
echo "${#key[@]}"
echo "${#key1[@]}"
And this prints empty
and not empty
respectively:
if (( ${#key[@]} == 0 )); then
echo empty
fi
if (( ${#key1[@]} != 0 )); then
echo not empty
fi
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With