x3nr0s
x3nr0s

Reputation: 2156

Bash - Checking each index of an array for empty values

With the following code I wish to check each index in an array for a null value, an empty string, or a string containing just white space. However it is not working.

test=( "apple" "orange" " ")
for i in ${test[@]};
do
    if [ -z "$i" ]; then
        echo "Oh no!"
    fi
done

It never enters the if block. What am I doing wrong?

Upvotes: 1

Views: 3100

Answers (2)

Inian
Inian

Reputation: 85683

You have a couple of errors in your script

  1. Un-quoted array expansion for i in ${test[@]};, during which the element with just spaces is just ignored by shell
  2. and -z option would just check for empty string and not a string with spaces

You needed to have,

test=( "apple" "orange" " ")
for i in "${test[@]}";
do
    # Replacing single-spaces with empty
    if [ -z "${i// }" ]; then
        echo "Oh no!"
    fi
done

The bash parameter-expansion syntax ${MYSTRING//in/by} (or) ${MYSTRING//in} is greedy in a way it replaces all occurrences. In your case, replacing all whites-spaces by nothing (null-string), so that you can match the empty string by -z

Upvotes: 3

Kaushik Nayak
Kaushik Nayak

Reputation: 31666

Use an empty string - not space when checking with -z . Enclose ${array[@]} with "" while looping.

test=( "apple" "orange" "")
for i in "${test[@]}";
do
    if [[ -z "$i" ]]; then
        echo "Oh no!"
    fi
done

Upvotes: 0

Related Questions