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.

3
  • == doesn't exist in dash if you're running Ubuntu. Use = instead. Commented Sep 4, 2013 at 7:21
  • actually I'm getting the errors because of != Commented Sep 4, 2013 at 7:23
  • I would suggest != is not the actual syntax error : pic.dhe.ibm.com/infocenter/aix/v7r1/… Commented Sep 4, 2013 at 7:28

4 Answers 4

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?

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

Comments

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"

Comments

0

Try substituting -NE for !=.

if-usage samples

Comments

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.