user3511965
user3511965

Reputation: 305

Issue with shell if statement

I have a shell script as follows (taken from some lecture slides):

#/bin/sh
echo -e "enter a number:\c"
read number
if [$number -ne 2]
  then
     echo "Number is not equals to 2"
fi

And I'm getting a syntax error where fi is. Any idea what the problem is?

Also, what does the extra term in echo -e "enter a number:\c" means (asides from the simple fact that it asks for a number)?

EDIT: now I did

#/bin/sh
echo -e "enter a number:\c"
read number
if [ "$number" -ne 2 ]
then
   echo "Number is not equals to 2"
fi

And I'm still getting the error...

Same goes for

#/bin/sh
read -p "enter a number: " number
if [ "$number" -ne 2 ]
then
   echo "Number is not equals to 2"
fi 

SOLVED: I've made a copying error there. Thanks for the input by the way, guys.

Upvotes: 1

Views: 65

Answers (1)

anubhava
anubhava

Reputation: 784938

Problem is this if condition:

if [$number -ne 2]

You need to put space after [ and before ] so use:

if [ "$number" -ne 2 ]

Your script can be rewritten as:

#/bin/sh
read -p "enter a number: " number
if [ "$number" -ne 2 ]
then
   echo "Number is not equals to 2"
fi

However if bash is available then better to switch to bash instead of old bourne shell.

Upvotes: 2

Related Questions