1

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?

1
  • 1
    A space isn't empty, also you need to quote ${test[@]} as it will currently strip out whitespace and empty values Commented Sep 15, 2017 at 10:48

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this is what I needed.
0

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

1 Comment

What if I wish to check for both empty string and white space?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.