0

Is there a difference between these two options in Bash:

# 1
if [[ "$VAR" ]]; then 

#2
if [[ -n "$VAR" ]]; then 

If not, are there situations that really require the -n option?

Steve Bennett
  • 114,604
  • 39
  • 168
  • 219
  • 2
    By the way, you don't need quotes around `$VAR` here. You do need quotes if you used `test` `[`, or for literals containing whitespace. The quotes are not doing any harm though. – cdarke Jul 16 '18 at 05:10
  • I'm not sure I will ever truly understand quotes and whitespace handling in Bash. :) – Steve Bennett Jul 16 '18 at 05:14
  • Possible duplicate of [Test for non-zero length string in Bash: \[ -n "$var" \] or \[ "$var" \]](https://stackoverflow.com/questions/3869072/test-for-non-zero-length-string-in-bash-n-var-or-var) – codeforester Jul 16 '18 at 05:38

1 Answers1

5

Since [[ is smarter than test about variables there are essentially no situations that require -n.

$ foo=-n
$ [[ $foo ]] ; echo $?
0
$ [[ -n ]] ; echo $?
bash: unexpected argument `]]' to conditional unary operator
bash: syntax error near `]]'
$ foo="-z bar"
$ [[ $foo ]] ; echo $?
0
$ [ $foo ] ; echo $?
1
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358