Code:
#!/bin/bash
EXISTS=""
echo ${#EXISTS} #print size of string
if [ -n $EXISTS ]; then
echo "It exists!"
else
echo "It is empty."
fi
if [ -z $EXISTS ]; then
echo "It is empty."
else
echo "It exists!"
fi
Output:
0
It exists!
It is empty.
From man bash
:
-z string
True if the length of string is zero.
-n string
True if the length of string is non-zero.
Could someone explain this behavior of -n to me, and why it doesn't agree with -z? Thanks!
[
and always usetest
(or even better, use[[ ... ]]
when available and POSIX compatibility isn't a concern). You're less likely to be surprised by how the arguments totest
are handled (because it actually looks like a command), and you don't need the ridiculous final]
argument whose only purpose is to further the illusion that[
is some sort of syntax.