6

I am writing a bash script, in which I am trying to check if there are particular parameters provided. I've noticed a strange (at least for me) behavior of [ -n arg ] test. For the following script:

#!/bin/bash

if [ -n $1 ]; then
    echo "The 1st argument is of NON ZERO length"
fi

if [ -z $1 ]; then
    echo "The 1st argument is of ZERO length"
fi

I am getting results as follows:

  1. with no parameters:

    xylodev@ubuntu:~$ ./my-bash-script.sh
    The 1st argument is of NON ZERO length
    The 1st argument is of ZERO length
    
  2. with parameters:

    xylodev@ubuntu:~$ ./my-bash-script.sh foobar
    The 1st argument is of NON ZERO length
    

I've already found out that enclosing $1 in double quotes gives me the results as expected, but I still wonder why both tests return true when quotes are not used and the script is called with no parameters? It seems that $1 is null then, so [ -n $1 ] should return false, shouldn't it?

  • Possible duplicate of [Check existence of input argument in a Bash shell script](http://stackoverflow.com/questions/6482377/check-existence-of-input-argument-in-a-bash-shell-script) – J.J. Hakala Jul 06 '16 at 19:04
  • Related: [Test for non-zero length string in Bash: -n “$var” or “$var”](https://stackoverflow.com/q/3869072/6862601). – codeforester Aug 31 '19 at 18:57

1 Answers1

10

Quote it.

if [ -n "$1" ]; then 

Without the quotes, if $1 is empty, you execute [ -n ], which is true*, and if $1 is not empty, then it's obviously true.

* If you give [ a single argument (excluding ]), it is always true. (Incidentally, this is a pitfall that many new users fall into when they expect [ 0 ] to be false). In this case, the single string is -n.

Kevin
  • 53,822
  • 15
  • 101
  • 132
  • I missed somehow that in the above case `-n` is considered as a string when no other parameters are provided for the `[` command. Clear now. Thanks for your explanation. – Benoît Xylo Dec 07 '13 at 14:51
  • So, what about the following case? It appears to be saying that '1' is null: $> b=1; if [ -n "$b" ]; then echo "true"; else echo "false"; fi true – Tom Russell Jul 07 '16 at 05:29
  • No @TomRussell - `-n` tests for _Non-zero length_, not _Nullness._ – PJSCopeland Apr 02 '17 at 22:29
  • 1
    `[ STRING ]` is actually given as an equivalent to `[ -n STRING ]` in [this table](http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html). – PJSCopeland Apr 02 '17 at 22:31