Search code examples
bashshellstring-length

How to use test with the nonzero flag -n


I am trying to check out test by using the sytax with the brackets [ and ].

The manpage of test says that -n can be used to check if the length of string is not zero:

 -n STRING
              the length of STRING is nonzero

In the opposite -z can be used ti check if the length of a string is zero:

-z STRING
              the length of STRING is zero

To understand how test works I crated an example with an empty variable foo which has the length of zero and a second variable bar with a length of one:

$ export foo
$ export bar=1
$ [ -n $bar ] ; echo $?
0
$ [ -n $foo ] ; echo $?
0
$ [ -z $bar ] ; echo $?
1
$ [ -z $foo ] ; echo $?
0

The first two tests with the -n are showing both zero as result. I suggested It would be zero for the first test and one for the second. The second test shows the result as suggested.


Solution

  • Try the following:

    [ -n "$foo" ] ; echo $?
    

    Since the $foo is an empty string, the

    [ -n $foo ] # without quotes
    

    becomes:

    [ -n ]
    

    Manual test(1) says:

    STRING equivalent to -n STRING
    

    So [ -n ] is treated not like [ -n "" ], but like [ "-n" ]