简体   繁体   中英

Compare two string variables in bash shell script

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM