1

I have this probleme and I don't understand why version bash :4.2.45

#!/bin/bash
echo "ca va (y/n)?"
read answer
if [ "$answer" == "y" ];then echo "yes"
else echo "no"
fi

this is the error

ca va (y/n)?
y
test.sh: 13: [: y: unexpected operator
no

thank a lot

cyphos
  • 51
  • 10

2 Answers2

3

That script works fine as a Bash script. However, the error you're getting is because you're running it as:

sh test.sh

rather than:

./test.sh

which means it's being run in /bin/sh mode. As explained in [ :Unexpected operator in shell programming, sh only accepts = and not ==.

Community
  • 1
  • 1
Joe
  • 29,416
  • 12
  • 68
  • 88
0

I tried it on my system, and it seems to work fine.

It could be because Bash 4.x is fussy about syntax (I'm on Bash 3.2), or it could be that you aren't specifying Bash when you run it:

$ sh test.sh

On many systems, this would run something like the Bourne shell. (On mine, it runs Bash in POSIX mode, so it still works). The == is not a valid test in Bourne shell (although it works in Bash and Kornshells). Using a single equals (=) instead of a double equals will solve this issue.

You can also try using the standard line breaks instead of the modern way lines are broken in if statements. Try this:

#!/bin/bash
echo "ca va (y/n)?"
read answer
if [ "$answer" = "y" ]
then
    echo "yes"
else
     echo "no"
fi
David W.
  • 105,218
  • 39
  • 216
  • 337