Sign up ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

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?


share|improve this question

2 Answers 2

Supposing your array is $errors, just check to see if the count of elements is zero.

if [ ${#errors[@]} -eq 0 ]; then
    echo "No errors, hooray"
    echo "Oops, something went wrong..."
share|improve this answer
Perfect, thank you Michael. – Marcos Sander Feb 11 '13 at 4:19
Please note that = is a string operator. It happens to work fine in this case, but I'd use the proper arithmetic operator -eq instead (just in case I'd want to switch to -ge or -lt, etc.). – musiphil Nov 8 '13 at 19:27

You can also consider the array as a simple variable. In that way, just using

if [ -z "$array" ]; then
    echo "Array empty"
    echo "Array non empty"

or using the other side

if [ -n "$array" ]; then
    echo "Array non empty"
    echo "Array empty"

Using this method can be useful to recover values from a function. The latter writes several return statements with echo and you catch them with this method:

return=($(checkDeps "dig" "whois" "hfjhj" "aaa"))

In this example I return elements which does not exist in the PATH. I can display all elements that doesn't exist with

echo ${return[@]}

or accessing manually to them e.g.:

echo ${return[0]}

or if I don't care simply check if there are elements that do not exist and exit:

if [ -n "$return" ]; then echo "quitting"; exit; fi
share|improve this answer
[ -z "$array" ] or [ -n "$array" ] doesn't work. Try array=('' foo); [ -z "$array" ] && echo empty, and it will print empty even though array is clearly not empty. – musiphil Aug 17 at 23:25

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.