shell - Testing against -n option in BASH scripts always returns true -
i writing bash script, in trying check if there particular parameters provided. i've noticed strange (at least me) behavior of [ -n arg ] test. following script:
#!/bin/bash if [ -n $1 ]; echo "the 1st argument of non 0 length" fi if [ -z $1 ]; echo "the 1st argument of 0 length" fi i getting results follows:
with no parameters:
xylodev@ubuntu:~$ ./my-bash-script.sh 1st argument of non 0 length 1st argument of 0 lengthwith parameters:
xylodev@ubuntu:~$ ./my-bash-script.sh foobar 1st argument of non 0 length
i've found out enclosing $1 in double quotes gives me results expected, still wonder why both tests return true when quotes not used , script called no parameters? seems $1 null then, [ -n $1 ] should return false, shouldn't it?
quote it.
if [ -n "$1" ]; without quotes, if $1 empty, execute [ -n ], true*, , if $1 not empty, it's true.
* if give [ single argument (excluding ]), true. (incidentally, pitfall many new users fall when expect [ 0 ] false). in case, single string -n.
Comments
Post a Comment