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.

Sign up to request clarification or add additional context in comments.

Comments

11

You have missed the quotes:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.