7

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?

2

1 Answer 1

12

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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.
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
No @TomRussell - -n tests for Non-zero length, not Nullness.
[ STRING ] is actually given as an equivalent to [ -n STRING ] in this table.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.