Test if string has non whitespace characters in Bash
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"
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\" " fidone
Output
Has length, and contain only whitespace " "Is either null or contain non-whitespace "abc " Is either null or contain non-whitespace ""
A non-bash specific, shell only variant:
case "$string" in *[!\ ]*) echo "known";; *) echo "unknown";;esac