18

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?

Elye
  • 53,639
  • 54
  • 212
  • 474

2 Answers2

43

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.

Elye
  • 53,639
  • 54
  • 212
  • 474
Bhakti Gandhi
  • 546
  • 4
  • 3
11

You have missed the quotes:

if [ "$1" = "-r" ]; then
codeforester
  • 39,467
  • 16
  • 112
  • 140
Slava Semushin
  • 14,904
  • 7
  • 53
  • 69