Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if array is empty in bash

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.

like image 834
Keru Chen Avatar asked Sep 12 '25 05:09

Keru Chen


1 Answers

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
like image 121
Ted Lyngmo Avatar answered Sep 14 '25 22:09

Ted Lyngmo