In bash, are [[ $variable ]]
and [[ -n $variable ]]
completely equivalent? It appears to be the case judging by the output below, but I see both forms of usage prevalent in shell scripts.
$ z="abra"
$ [[ $z ]]
$ echo $?
0
$ [[ -n $z ]]
$ echo $?
0
$ z=""
$ [[ $z ]]
$ echo $?
1
$ [[ -n $z ]]
$ echo $?
1
$ unset z
$ [[ $z ]]
$ echo $?
1
$ [[ -n $z ]]
$ echo $?
1
Best Answer
[ "$var" ]
is equivalent to[ -n "$var" ]
in bash and most shells nowadays. In other older shells, they're meant to be equivalent, but suffer from different bugs for some special values of "$var" like=
,(
or!
.I find
[ -n "$var" ]
more legible and is the pendant of[ -z "$var" ]
.[[ -n $var ]]
is the same as[[ $var ]]
in all the shells where that non-standard ksh syntax is implemented.test "x$var" != x
would be the most reliable if you want to be portable to very old shells.