Test if string has non whitespace characters in Bash
You can use bash's regex syntax.
It requires that you use double square brackets [[ ... ]]
, (more versatile, in general).
The variable does not need to be quoted. The regex itself must not be quoted
for str in " " "abc " "" ;do
if [[ $str =~ ^\ +$ ]] ;then
echo -e "Has length, and contain only whitespace \"$str\""
else
echo -e "Is either null or contain non-whitespace \"$str\" "
fi
done
Output
Has length, and contain only whitespace " "
Is either null or contain non-whitespace "abc "
Is either null or contain non-whitespace ""
Many of these answers are far more complex, or far less readable, than they should be.
[[ $string = *[[:space:]]* ]] && echo "String contains whitespace"
[[ $string = *[![:space:]]* ]] && echo "String contains non-whitespace"