如何在Bash的'if'语句中比较两个字符串变量? [重复]

泪湿孤枕 提交于 2020-08-13 12:36:16

问题:

This question already has an answer here: 这个问题已经在这里有了答案:

I'm trying to get an if statement to work in Bash (using Ubuntu ): 我正在尝试让if语句在Bash中工作(使用Ubuntu ):

#!/bin/bash

s1="hi"
s2="hi"

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

I've tried various forms of the if statement, using [["$s1" == "$s2"]] , with and without quotes, using = , == and -eq , but I still get the following error: 我已经尝试过各种形式的if语句,使用[["$s1" == "$s2"]] ,使用和不使用引号,使用===-eq ,但是仍然出现以下错误:

[hi: command not found [hi:找不到命令

I've looked at various sites and tutorials and copied those, but it doesn't work - what am I doing wrong? 我查看了各种站点和教程并复制了这些站点和教程,但是它不起作用-我在做什么错?

Eventually, I want to say if $s1 contains $s2 , so how can I do that? 最终,我想说一下$s1包含$s2 ,那我该怎么做呢?

I did just work out the spaces bit.. :/ How do I say contains? 我只是算出空格位..:/我怎么说包含?

I tried 我试过了

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

but it didn't work. 但这没用。


解决方案:

参考一: https://stackoom.com/question/Hwob/如何在Bash的-if-语句中比较两个字符串变量-重复
参考二: https://oldbug.net/q/Hwob/How-do-I-compare-two-string-variables-in-an-if-statement-in-Bash-duplicate
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!