0

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.

Uttam Malakar
  • 684
  • 1
  • 6
  • 15

4 Answers4

2

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?

Community
  • 1
  • 1
dogbane
  • 266,786
  • 75
  • 396
  • 414
1

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"
Shuhail Kadavath
  • 448
  • 3
  • 13
0

Try substituting -NE for !=.

if-usage samples

vikingsteve
  • 38,481
  • 23
  • 112
  • 156
0

This should work:

#!/bin/sh
echo "start"
if [ $# -ne 2 -o $1 -ne "first" -o $1 -ne "second" ]
then
    echo "Error"
fi
echo "done"
Vijay
  • 65,327
  • 90
  • 227
  • 319