Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
508 views
in Technique[技术] by (71.8m points)

bash - 如何在Bash的'if'语句中比较两个字符串变量? [重复](How do I compare two string variables in an 'if' statement in Bash? [duplicate])

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.

(但这没用。)

  ask by Mr Shoubs translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For string comparison, use:

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

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

For the a contains b , use:

(对于a包含b ,请使用:)

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

(and make sure to add spaces between the symbols):

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

bad:

(坏:)

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

good:

(好:)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...