Bash function for zero length string or with whitespace

Viewed 168

In bash I can use -z string and -n string to see if the string length is zero or not. Would like to write a bash function that returns true or false, not only if length is zero but also if it is all whitespace. Or is there a way without needing a function?

3 Answers

You can use a regular expression:

if [[ $string =~ ^" "*$ ]]

or you can remove all the spaces before testing with -z:

if [[ -z "${string// /}" ]]

If you want it to be portable to non-bash shells (e.g. dash, which is the default /bin/sh on some Linux distros), you can use this:

if [ "$variable" = "${variable#*[![:space:]]}" ]; then

Explanation: ${variable%pattern} will remove a match of the pattern from the beginning of the variable's value if there is such a match. The pattern *[![:space:]] will match from the beginning of the string through the first non-space character (if there are any non-space characters in the string). Therefore, if there's at least one non-space character, the pattern will match and the variable's value will change, so the = test will fail. On the other hand if the string doesn't contain any non-space characters, the pattern won't match, the variable won't be modified, and the = test will succeed.

For completeness, you can also use case for this:

case "$variable" in
    *[![:space:]]* ) echo "variable is NOT empty" ;;
    * ) echo "variable IS empty" ;;
esac

Either of these should work in any POSIX-compliant shell.

Use the exit status of grep -Pq '\S', which is true if there is at least 1 non-whitespace character, and false otherwise:

grep -Pq '\S' <<< " " && echo "not all whitespace" || echo "all whitespace"
# all whitespace

grep -Pq '\S' <<< "" && echo "not all whitespace" || echo "all whitespace" 
# all whitespace

grep -Pq '\S' <<< "a" && echo "not all whitespace" || echo "all whitespace"
# not all whitespace

Here, GNU grep uses the following options:
-P : Use Perl regexes.
-q : Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found.

\S : non-whitespace character.

SEE ALSO:
grep manual
perlre - Perl regular expressions

Related