Reputation: 11
The output I get is sh21.sh: 5: [: xhi: unexpected operator no match
My code is as follows:
#!/bin/bash
s1="hi"
s2="hi"
s3="hello"
if [ "x$s1" == "x$s2" ]
then
echo match
else
echo no match
fi
Please explain to me what I am doing wrong.
Upvotes: 0
Views: 302
Reputation: 84652
if [ "x$s1" == "x$s2" ]
should be
if [ "x$s1" = "x$s2" ]
There is only 1 equal sign when using test
or [
in shell programming. Bash allows ==
with [[
, but it should not be used with [
. Both test
and [
are equivalent and are the POSIX test utility. Bash has the [[
operator that is not the same. There are subtle differences in syntax, quoting requirements and available operators between them.
Upvotes: 2
Reputation: 113994
If you are going to use bashisms in your script, it is important to use bash. Your code works fine with bash:
$ bash sh21.sh
match
It fails with dash (which is the sh
on debian-like systems):
$ sh sh21.sh
sh21.sh: 5: [: xhi: unexpected operator
no match
==
is a bashism, meaning it only works under bash or similar shells. If you want a POSIX compatible script, use =
. If not, run the script under bash.
Upvotes: 3
Reputation: 4048
Maybe you are using Debian based distros, and the default shell is dash, not bash
Check your shell
ls -l /bin/sh /bin/bash
Run the script with bash
bash sh21.sh
Upvotes: 0