The easy way to check that a string only contains characters in an authorized set is to test for the presence of unauthorized characters. Thus, instead of testing whether the string only contains spaces, test whether the string contains some character other than space. In bash, ksh or zsh:
if [[ $param = *[!\ ]* ]]; then
echo "\$param contains characters other than space"
echo "\$param consists of spaces only"
“Consists of spaces only” includes the case of an empty (or unset) variable.
You may want to test for any whitespace character. Use
[[ $param = *[^[:space:]]* ]] to use locale settings, or whatever explicit list of whitespace characters you want to test for, e.g.
[[ $param = *[$' \t\n']* ]] to test for space, tab or newline.
Matching a string against a pattern with
[[ … ]] is a ksh extension (also present in bash and zsh). In any Bourne/POSIX-style, you can use the
case construct to match a string against a pattern. Note that standard shell patterns use
! to negate a character set, rather than
^ like in most regular expression syntaxes.
case "$param" in
*[!\ ]*) echo "\$param contains characters other than space";;
*) echo "\$param consists of spaces only";;
To test for whitespace characters, the
$'…' syntax is specific to ksh/bash/zsh; you can insert these characters in your script literally (note that a newline will have to be within quotes, as backslash+newline expands to nothing), or generate them, e.g.
whitespace=$(printf '\n\t ')
case "$param" in
*[!$whitespace]*) echo "\$param contains non-whitespace characters";;
*) echo "\$param consists of whitespace only";;
-z STRING - the length of STRING is zero. If you want to remove all spaces in
trim()function built-in to any *nix at all? So many different hacks to achieve something so simple...
[[ ! -z $param ]]is equivalent to
test ! -z $param.