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"
else
echo "\$param consists of spaces only"
fi
“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 =
inside [[ … ]]
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";;
esac
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";;
esac
man test
:-z STRING - the length of STRING is zero
. If you want to remove all spaces in$param
, use${param// /}
– dchirikov Jul 28 '14 at 09:27trim()
function built-in to any *nix at all? So many different hacks to achieve something so simple... – ADTC Mar 29 '16 at 03:09[[ ! -z $param ]]
is equivalent totest ! -z $param
. – Noah Sussman May 31 '18 at 15:48! [ -z $param ] 2>/dev/null && echo no content
'[' as a program will ignore multiple spaces between arguments and will fail if wrong number of arguments is provided with a result '1'. The same as if test -z was false. There is a special case of second argument '-o', but besides that, I would also argue against using it as even if its "working", it's not doing what it's intended to do. – papo Jan 25 '21 at 01:16[
is equivalent totest
. Sometimes it used to be a symlink. But[[
is BASH specific and there are many differences to programtest
. The reason of creating [[ was to make it easier to construct conditions. For that purpose it can't be the same as '[' ortest
. – papo Jan 25 '21 at 01:22