0

Hello I have a simple example which I am confused about:

#!bin/bash
#test_str is a script to test whether a string is empty or not

x=''
if [ -n $x ]
then  
    echo "'$x' is not empty"
else 
    echo "'$x' empty"
fi

chmod u+x test_str
./test_str

The output:

'' is not empty
  • This occurs also if I've not declared a variable (x here).

  • If I use the flag -z to test for emptiness it works fine:

      if [ -z $x ]
      then  
          echo "'$x' is  empty"
      else 
          echo "'$x' not empty"
      fi
    

The output:

'' is empty
  • So how can I use -n correctly? Thank you!
Maestro
  • 2,512
  • 9
  • 24
  • 3
    Quote it! `[ -n "$x" ]` without it, construct is evaluated as `[ -n ]` which is _always_ true – Inian Sep 24 '20 at 11:06
  • Duplicate maybe https://stackoverflow.com/questions/6852612/test-for-empty-string-with-x it's hard to find a duplicate when searching for `-n` :/ – KamilCuk Sep 24 '20 at 11:07
  • @Inian: Can you explain more please. or add it as an answer? – Maestro Sep 24 '20 at 11:09
  • @Inian: It works fine thanks. One last question: should I uses `""` for the flag `-z` too or not? and if not why? – Maestro Sep 24 '20 at 11:12
  • When in doubt, always look up the manual - https://www.gnu.org/software/bash/manual/html_node/Bash-Conditional-Expressions.html . Search for `-z string` and `-n string` – Inian Sep 24 '20 at 11:14
  • @Maestro : You will notice, that i.e. [ -ge ] also is true. See _man test_, where it says: _-n STRING : the length of STRING is nonzero_ and in the next line: _STRING equivalent to -n STRING_ Since your `[ -n $x ]` is, after expansion of the empty x, equiavlent to `test -n`, the first variant does not apply (there is no _STRING_ anymore), but the second does: The statement is interpreted as `test -n -n`, i.e. whether the string _-n_ is not empty. – user1934428 Sep 24 '20 at 12:29

1 Answers1

3

This is because [ -n $n ] is expanded to [ -n ] so there is nothing to compare and it will return true.

Instead, you should use [ -n "${n}" ] to prevent such errors and to prevent globbing.

Jens
  • 69,818
  • 15
  • 125
  • 179
Emanuel Bennici
  • 426
  • 3
  • 13