While dealing with arrays in bash, you may find yourself in a situation where you have to check whether an array is empty.
Doing that is pretty simple actually. Here's a pseudocode:
if [[ -z "${array[@]}" ]]; then
echo "empty array"
fi
See the trick? I "expanded" the array and checked if the string was empty using the -z
Bash conditional operator.
You could also get the bash array length and check if it is zero or not.
Bash script examples for checking if an array is empty
Let's understand the above example a bit better. I will explain what is happening with a demonstration.
#!/usr/bin/env bash
array1=('1' '23' '4' '56' '78' '9' '0')
array2=()
echo "array1: '${array1[@]}'"
echo "array2: '${array2[@]}'"
In this demonstration script, I have taken two arrays; one is empty and another is populated with strings.
Upon running this script, I get the following output:
array1: '1 23 4 56 78 9 0'
array2: ''
Now, the -z
conditional operator in Bash is actually used to check if a string is empty or not. So when the -z
operator is used with a variable, it is not checking if the variable is empty or not, but in reality, it is checking if the assigned string is empty or not.
So now that you have seen that using the @
expression, which displays the entire array. Then, that is used to check if an array (which is technically a string of strings) is empty or not.
Let's finally understand this with an example program:
#!/usr/bin/env bash
array1=('1' '23' '4' '56' '78' '9' '0')
array2=()
if [[ -z "${array1[@]}" ]]; then
echo "array1 is empty"
fi
if [[ -z "${array2[@]}" ]]; then
echo "array2 is empty"
fi
Now that you understand the logic behind it, can you guess the output? Either way, the output is as follows:
array2 is empty
π‘ Taking a shortcut
Though an if
statement in Bash allows you to perform more than one task for a conditional check; if you want to perform only one thing, there is a neat shortcut for that.
#!/usr/bin/env bash
array=()
[[ -z "${array[@]}" ]] && echo "array is empty"
Here, based on if the array is empty, I only want to print that it indeed is empty. I do so by using only the test operator ([
and ]
) and put a logical AND (&&
) followed by the echo
statement.
Conclusion
If you would rather just ensure that the array is not empty, you can use the -n
instead of -z
.
if [[ -n "${array[@]}" ]]; then
#do something with the array
fi
Checking if an array is empty or not is just as easy as checking if a bash variable is empty or not. The only additional step to perform this task is to use the @
expression to expand the array.
Happy scripting! :)