[ :Unexpected operator in shell programming

LinuxBashShell

Linux Problem Overview


My code:

    #!/bin/sh
    #filename:choose.sh
    read choose
    [ "$choose" == "y" -o "$choose" == "Y" ] && echo "Yes" && exit 0
    [ "$choose" == "n" -o "$choose" == "N" ] && echo "No"  && exit 0
    echo "Wrong Input" && exit 0

But when I execute

    sh ./choose.sh

terminal prompt me that

   [: 4: n: :Unexpected operator
   [: 5: n: :Unexpected operator

Is there any mistake in my bash script? Thanks!

Linux Solutions


Solution 1 - Linux

There is no mistake in your bash script. But you are executing it with sh which has a less extensive syntax ;)

So, run bash ./choose.sh instead :)

Solution 2 - Linux

POSIX sh doesn't understand == for string equality, as that is a bash-ism. Use = instead.

The other people saying that brackets aren't supported by sh are wrong, btw.

Solution 3 - Linux

To execute it with Bash, use #!/bin/bash and chmod it to be executable, then use

./choose.sh

Solution 4 - Linux

you can use case/esac instead of if/else

case "$choose" in
  [yY]) echo "Yes" && exit;;
  [nN]) echo "No" && exit;;
  * ) echo "wrong input" && exit;;
esac

Solution 5 - Linux

you have to use bash instead or rewrite your script using standard sh

sh -c 'test "$choose" = "y" -o "$choose" = "Y"'

Solution 6 - Linux

In fact the "[" square opening bracket is just an internal shell alias for the test command.

So you can say:

test -f "/bin/bash" && echo "This system has a bash shell"

or

[ -f "/bin/bash" ] && echo "This system has a bash shell"

... they are equivalent in either sh or bash. Note the requirement to have a closing "]" bracket on the "[" command but other than that "[" is the same as "test". "man test" is a good thing to read.

Solution 7 - Linux

Do not use any reserved keyword as the start of any variable name: eg HOSTNAME will fail as HOST {TYPE|NAME} are reserved

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionkit.yangView Question on Stackoverflow
Solution 1 - LinuxWolphView Answer on Stackoverflow
Solution 2 - LinuxNietzche-jouView Answer on Stackoverflow
Solution 3 - LinuxJack ScottView Answer on Stackoverflow
Solution 4 - Linuxghostdog74View Answer on Stackoverflow
Solution 5 - LinuxAnycornView Answer on Stackoverflow
Solution 6 - LinuxdelatbabelView Answer on Stackoverflow
Solution 7 - LinuxAp.MuthuView Answer on Stackoverflow