Q:

Check if array is empty in Bash

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?

A:

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"
else
    echo "Oops, something went wrong..."
fi

A:

I generally use arithmetic expansion in this case:
if (( ${#a[@]} )); then
    echo not empty
fi

A:

You can also consider the array as a simple variable. In that way, just using 
if [ -z "$array" ]; then
    echo "Array empty"
else
    echo "Array non empty"
fi

or using the other side
if [ -n "$array" ]; then
    echo "Array non empty"
else
    echo "Array empty"
fi

The problem with that solution is that if an array is declared like this: array=('' foo). These checks will report the array as empty, while it is clearly not. (thanks @musiphil!)
Using [ -z "$array[@]" ] is clearly not a solution neither. Not specifying curly brackets tries to interpret $array as a string ([@] is in that case a simple literal string) and is therefore always reported as false: "is the literal string [@] empty?" Clearly not.

