Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"" on $1, why does bash behave like this?

Tags:

bash

if a script has

if [ $1 == "-?" ]; then #line 4
    echo "usage: ...."
fi

when the script get runs without any parameter, it will complain that

./script.sh: line 4: [: ==: unary operator expected

but if instead

if [ "$1" == "-?" ]; then #line 4
    echo "usage: ...."
fi

then everything's fine

why is that?

thanks

like image 200
Augie Avatar asked Dec 27 '22 18:12

Augie


2 Answers

If the first argument is missing or empty, your first script evaluates to:

if [ == "-?" ] ; then

... which is a syntax error. As you noticed, to prevent that you need to make use of "", then it evaluates to:

if [ "" == "-?" ] ; then

AFAIK this is due to the way the original Bourne shell was working. You should make it a habit of enclosing variables in "" to also work correctly with arguments that have spaces in it. For example, if you would call your script like this:

./myScript "first argument has spaces"

Then your first script would evaluate to:

if [ first argument has spaces == "-?" ] ; then

which is also a syntax error. Also things like rm $1 will not do what you want if you pass filenames with spaces. Do rm "$1" instead.

like image 90
DarkDust Avatar answered Jan 16 '23 20:01

DarkDust


Because [ replaces the values before executing. [[ doesn't, so will work as expected.

like image 43
Ignacio Vazquez-Abrams Avatar answered Jan 16 '23 21:01

Ignacio Vazquez-Abrams