Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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
share|improve this question
    
Hm. Interesting. Outputs from [[ -n $(echo -ne "\0") ]]; echo $? and [ -n $(echo -ne "\0") ]; echo $? differ –  dchirikov Jan 30 '13 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. –  Stéphane Chazelas Jan 30 '13 at 20:29
add comment

2 Answers 2

up vote 3 down vote accepted

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

share|improve this answer
add comment

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

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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.