简体   繁体   English

比较bash shell脚本中的两个字符串变量

[英]Compare two string variables in bash shell script

The output I get is sh21.sh: 5: [: xhi: unexpected operator no match 我得到的输出是sh21.sh:5:[:xhi:意外的运算符不匹配

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. 如果要在脚本中使用bashism,则使用bash很重要。 Your code works fine with bash: 您的代码可以与bash一起正常工作:

$ bash sh21.sh
match

It fails with dash (which is the sh on debian-like systems): 它失败并带有破折号(这是类似debian的系统上的sh ):

$ sh sh21.sh
sh21.sh: 5: [: xhi: unexpected operator
no match

== is a bashism, meaning it only works under bash or similar shells. ==是一种bashism,意味着它仅在bash或类似shell下工作。 If you want a POSIX compatible script, use = . 如果需要POSIX兼容脚本,请使用= If not, run the script under bash. 如果不是,请在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. 在外壳编程中使用test[时,只有1个等号。 Bash allows == with [[ , but it should not be used with [ . Bash允许[[ ==使用== ,但不应与[ Both test and [ are equivalent and are the POSIX test utility. test[都是等效的,并且是POSIX测试实用程序。 Bash has the [[ operator that is not the same. Bash的[[运算符相同。 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 也许您正在使用基于Debian的发行版,并且默认的shell是dash ,而不是bash

Check your shell 检查你的外壳

ls -l /bin/sh /bin/bash

Run the script with bash bash运行脚本

bash sh21.sh

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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