19

I have my shell script, myscript.sh below

#!/bin/sh
if [ $1 = "-r" ]; then
    echo "I am here"
fi

If I run with . myscript.sh -r, it works well with message I am here.

But if I just run with . myscript.sh, it complaints

-bash: [: =: unary operator expected

What's missing in my script?

0

2 Answers 2

44

You would need to add quotes around $1.

if [ "$1" = "-r" ]; then
    echo "I am here"
fi

When $1 is empty you are getting if [ = "-r"] which is a syntax error.

11

You have missed the quotes:

if [ "$1" = "-r" ]; then
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.