Augie
Augie

Reputation: 123

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

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

Upvotes: 4

Views: 149

Answers (2)

DarkDust
DarkDust

Reputation: 92384

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.

Upvotes: 5

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799082

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

Upvotes: 5

Related Questions