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?
You have a couple of errors in your script
for i in ${test[@]};
, during which the element with just spaces is just ignored by shell -z
option would just check for empty string and not a string with spacesYou 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