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 [
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.
Quoting. You have to quote variables that you use in [
:
$ VAR=
$ [ -n $VAR ]
$ echo $?
0
$ [ -n "$VAR" ]
$ echo $?
1