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:
with no parameters:
xylodev@ubuntu:~$ ./my-bash-script.sh The 1st argument is of NON ZERO length The 1st argument is of ZERO length
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?