0
#!/bin/bash
if [$# -ne 1];
then
  echo "/root/script.sh a|b"
else if [$1 ='a'];
then
  echo "b"
else if [$1 ='b']; then
  echo "a"
else 
  echo "/root/script.sh a|b"
fi

I'm getting below error while run above script in Linux.

bar.sh: line 2: [: S#: integer expression expected
a

Could you please help to remove this error?

2
  • 3
    Gee, I do hope you are not practicing your shell scripting in the root account. Commented Jul 22, 2012 at 18:35
  • 1
    The S# in the error message looks like you misspelled $# either when transcribing the error message or in the code. Commented Jul 22, 2012 at 19:03

2 Answers 2

5
if [$# -ne 1];

[ and ] requires spacing. Example:

if [ $# -ne 1 ];

And else if should be elif

#!/bin/bash
if [ "$#" -ne 1 ];
then
  echo "/root/script.sh a|b"
elif [ "$1" ='a' ];
then
  echo "b"
elif [ "$1" ='b' ]; then
  echo "a"
else
  echo "/root/script.sh a|b"
fi

Do not forget to quote variables. It is not every time necessary, but recommended.

Question: Why do i have -1?

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

4 Comments

The semicolons after the ]s are only necessary if you put the then on the same line.
I know, but this is no problem so i did not change it.
Doh! I didn't notice that that was how it was in the original script.
You also need spaces around the operators (including after the =) inside [ ... ]
2

Bash doesn't allow else if. Instead, use elif.

Also, you need spacing within your [...] expression.

#!/bin/bash
if [ $# -ne 1 ];
then
  echo "/root/script.sh a|b"
elif [ $1 ='a' ];
then
  echo "b"
elif [ $1 ='b' ]; then
  echo "a"
else 
  echo "/root/script.sh a|b"
fi

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.