Uttam Malakar
Uttam Malakar

Reputation: 714

Error executing shell script

I am trying to execute the following shell script

#!/bin/sh
echo "start"
if [ $# != 2 || $1 != "first" || $1 != "second" ]
then
    echo "Error"
fi
echo "done"

and I'm getting the following output: start ./autobuild.sh: line 3: [: missing `]' ./autobuild.sh: line 3: !=: command not found ./autobuild.sh: line 3: !=: command not found done

I have no idea how to resolve the errors. Even if I use -ne instead of !=, I get the same errors. Please help.

Upvotes: 0

Views: 96

Answers (4)

Shuhail Kadavath
Shuhail Kadavath

Reputation: 448

While OR ing the conditions should be seperate as follows :

#!/bin/sh
echo "start"
if [ $# != 2]  || [ $1 != "first" ] || [ $1 != "second" ]
then
    echo "Error"
fi
echo "done"

Upvotes: 1

Vijay
Vijay

Reputation: 67291

This should work:

#!/bin/sh
echo "start"
if [ $# -ne 2 -o $1 -ne "first" -o $1 -ne "second" ]
then
    echo "Error"
fi
echo "done"

Upvotes: 0

dogbane
dogbane

Reputation: 274828

Your syntax is incorrect. If you want multiple conditions in an if statement you need to have multiple [] blocks. Try:

if [ $# != 2 ] || [ $1 != "first" ] || [ $1 != "second" ]

But, it's better to use [[ (if your shell supports it) as it is safer to use. I would go for:

if [[ $# -ne 2 || $1 != "first" || $1 != "second" ]]

See this question on brackets: Is [[ ]] preferable over [ ] in bash scripts?

Upvotes: 2

vikingsteve
vikingsteve

Reputation: 40438

Try substituting -NE for !=.

if-usage samples

Upvotes: 0

Related Questions