如何比较Bash中'if'语句中的两个字符串变量?

我试图让if语句在Bash中工作(使用Ubuntu):

#!/bin/bash

s1="hi"
s2="hi"

if ["$s1" == "$s2"]
then
  echo match
fi

我试过各种形式的if语句,使用[["$s1" == "$s2"]] ,带和不带引号,使用===-eq ,但我仍然遇到以下错误:

[嗨:找不到命令

我查看了各种网站和教程并复制了这些内容,但它不起作用 - 我做错了什么?

最后,我想说,如果$s1包含$s2 ,那么我该怎么做?

我只是制定出空间位..:/我怎么说包含?

我试过了

if [[ "$s1" == "*$s2*" ]]

但它不起作用。


对于字符串比较,请使用:

if [ "$s1" == "$s2" ]

对于a包含b ,请使用:

if [[ $s1 == *"$s2"* ]]

(并确保在符号之间添加空格):

坏:

if ["$s1" == "$s2"]

好:

if [ "$s1" == "$s2" ]

你需要空间:

if [ "$s1" == "$s2" ]

您应该小心,在'[''和双引号之间留有一个空格,其中变量包含以下内容:

if [ "$s1" == "$s2" ]; then
#   ^     ^  ^     ^
   echo match
fi

^ s显示您需要离开的空白处。

链接地址: http://www.djcxy.com/p/24141.html

上一篇: How do I compare two string variables in an 'if' statement in Bash?

下一篇: How to avoid .pyc files?