Take the 2-minute tour ×
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

closed as off topic by mdpc, EEAA, Ward, Khaled, dunxd Feb 11 '13 at 10:26

Questions on Server Fault are expected to relate to server, networking, or related infrastructure administration within the scope defined by the community. Consider editing the question or leaving comments for improvement if you believe the question can be reworded to fit within the scope. Read more about reopening questions here.If this question can be reworded to fit the rules in the help center, please edit the question.

1 Answer 1

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

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