8

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
2
  • Hm. Interesting. Outputs from [[ -n $(echo -ne "\0") ]]; echo $? and [ -n $(echo -ne "\0") ]; echo $? differ Commented Jan 30, 2013 at 19:31
  • @dchirikov, that's because in the second one, you forgot to quote the command substitution, so it ended up being [ -n ], the same [ -n -n ]. In shells other than zsh, command (even builtin) arguments or shell variables can't contain NUL characters. Commented Jan 30, 2013 at 20:29

2 Answers 2

4

[ "$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.

1

According to Test for non-zero length string in bash: [ -n “$var” ] or [ “$var” ], yes, they are equivalent.

They are equivalent even quoting the name of the variable.

Important to notice: the name of the question I cite refers only to [, but the answer considers both [ and [[.

4
  • 1
    But [[]] is not the equivalent of [] :) Commented Jan 30, 2013 at 19:32
  • No, they aren't. But in the answer I cite, both forms are considered. Commented Jan 30, 2013 at 19:35
  • Behaviour in testing "\0" as a variable is different. Operator [] gives 0 or 1. And [[]] gives 1 in both cases. Commented Jan 30, 2013 at 19:55
  • +1 for the link which is very informative however Stephane Chazelas's answer, which I accepted, is more to the point. Commented Jan 30, 2013 at 20:40

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.