You want the -n
test ("true if the length of the given string is non-zero"), which is the opposite of the -z
test ("true if the length of the given string is zero").
The -p
test is something completely different ("true if the given file exists and is a named pipe").
This information is available to you in an interactive bash
shell by typing
help test
which will give you the documentation for the built-in test
utility (which [
is another variant of; see help [
, and which [[
uses the same tests as; see help [[
). You may also have a look at the bash
manual on your system (man bash
), where this is documented under the section titled "CONDITIONAL EXPRESSIONS".
Your code would therefore be one of
if [[ -n $var ]]; then ...; fi
if [ -n "$var" ]; then ...; fi
if test -n "$var"; then ...; fi
Having said that, I see nothing wrong with
if [[ ! -z $var ]]; then ...; fi
if you, for example, want to make sure that the value is empty and want to output an error message if it isn't empty. The code would then serve as documenting what your intention is: "If this is not empty, there is something wrong". This is a matter of taste.
[
istest
so you can doman test
. This will give you what you are looking for. If it did not then you can doman bash | less -r "+/\[\["
, then press / Return to find next match (about 3 or 4 times), until you find what you need. – ctrl-alt-delor Mar 04 '20 at 07:32[ "$string" ]
ortest "$string"
is the shortest, nicest and most standard. Do not omit the quotes. And yes, that works even if$string
looks like an option. If you have to code for pre-posix shells, use[ "x$string" != x ]
. That's the most portable. – Mar 04 '20 at 10:58[[
...]]
is not recommended since this is a ksh88 enhancement that intentionally has not been added to the POSIX standard. So better usetest
of it's alias[
. – schily Mar 04 '20 at 13:37-n
or-z
, or variations on why[ -n $v ]
turns into[ -n ]
and succeeds. – Mar 05 '20 at 08:50