user6857534
user6857534

Reputation: 3

Bash nonzero test case (-n), [ and [[ are doing different things

Usually i only use [[ for all kinds of test cases, because it's the most advanced way and it's more safe to use (Regex, ...). I know that [[ executes different code than [, but according to the manpage and various documentations, it should at least handle options like "-n" the same way, but it doesn't.

-n STRING the length of STRING is nonzero

VAR=

if [[ -n $VAR ]]
then
        echo "\$VAR is nonzero"
else
        echo "\$VAR is zero"
fi

$VAR is zero

VAR=

if [ -n $VAR ]
then
        echo "\$VAR is nonzero"
else
        echo "\$VAR is zero"
fi

$VAR is nonzero

How is this even possible?

bash 4.1.2(1)

Upvotes: 0

Views: 76

Answers (2)

l0b0
l0b0

Reputation: 58908

Quoting. You have to quote variables that you use in [:

$ VAR=    
$ [ -n $VAR ]
$ echo $?
0
$ [ -n "$VAR" ]
$ echo $?
1

Upvotes: 0

Tom Fenech
Tom Fenech

Reputation: 74685

I think that your problem is related to quotes.

When you use [ -n $VAR ] the command that is executed won't contain any argument where $VAR should be:

$ set -x
$ [ -n $VAR ]
+ '[' -n ']'

This means that you are essentially testing whether the string -n is non-empty, because the following two tests are equivalent:

[ string ]    # is a shorthand for
[ -n string ] # which is always true!

If you use quotes, then you get different behaviour:

$ [ -n "$VAR" ]
+ '[' -n '' ']'

Now you are testing whether the variable is non-empty, so you get the expected behaviour.

Upvotes: 1

Related Questions