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.
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.
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.
/bin/bash and Bash actually tolerates == with [ as well. I'm guessing the OP incorrectly runs the script with sh scriptname., though.test or [ that doesn't apply to any other program. (In fact, there is no requirement for test or [ to even be a built-in command; both probably exist in your file system.)utility -- fixed.
=in POSIX test construct.testis a program.testor[in a shell, you are telling the shell to test what follows. (I think[is actually an alias oftest) POSIX shell is just that subset of features that is more or less guaranteed to work with every shell. Things like[[are referred to as Bashisms because they only work with bash and are not guaranteed to be portable between shells. Oh, and yes I see what you are saying,testis a program along with all the others that make up the shell. When I say construct, I just mean what the shell uses.