Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

-bash: [: =: unary operator expected. when no parameter given [duplicate]

Tags:

bash

shell

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?

like image 657
Elye Avatar asked Mar 06 '17 23:03

Elye


2 Answers

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.

like image 186
Bhakti Gandhi Avatar answered Oct 31 '22 07:10

Bhakti Gandhi


You have missed the quotes:

if [ "$1" = "-r" ]; then
like image 10
Slava Semushin Avatar answered Oct 31 '22 08:10

Slava Semushin