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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4277665/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 19:54:00  来源:igfitidea点击:

How do I compare two string variables in an 'if' statement in Bash?

bashif-statementscripting

提问by Mr Shoubs

I'm trying to get an ifstatement to work in Bash(using Ubuntu):

我正在尝试获得ifBash 中工作的声明(使用Ubuntu):

#!/bin/bash

s1="hi"
s2="hi"

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

I've tried various forms of the ifstatement, 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

[嗨:找不到命令

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 $s1contains $s2, so how can I do that?

最后,我想说 if $s1contains $s2,那我该怎么做呢?

I did just work out the spaces bit... :/ How do I say contains?

我只是算出空格位...:/我怎么说contains

I tried

我试过

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

but it didn't work.

但它没有用。

回答by moinudin

For string comparison, use:

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

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

For the acontains b, use:

对于acontains b,请使用:

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

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

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

Bad:

坏的:

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

Good:

好的:

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

回答by unwind

You need spaces:

你需要空格:

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

回答by trejo08

You should be careful to leave a space between the sign of '[' and double quotes where the variable contains this:

您应该小心在 '[' 的符号和包含以下变量的双引号之间留一个空格:

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

The ^s show the blank spaces you need to leave.

^S显示你需要离开的空白。

回答by Abderrazak BOUADMA

I suggest this one:

我推荐这个:

if [ "$a" = "$b" ]

Notice the white space between the openning/closing brackets and the variables and also the white spaces wrapping the '=' sign.

请注意开始/结束括号和变量之间的空白以及包裹“=”符号的空白。

Also, be careful of your script header. It's not the same thing whether you use

另外,请注意您的脚本标题。你用不一样

#!/bin/bash

or

或者

#!/bin/sh

Here's the source.

这是来源

回答by Mike Q

Bash 4+ examples. Note: not using quotes will cause issues when words contain spaces, etc. Always quote in Bash IMO.

Bash 4+ 示例。注意:当单词包含空格等时,不使用引号会导致问题。在 Bash IMO 中始终引用。

Here are some examples Bash 4+:

以下是 Bash 4+ 的一些示例:

Example 1, check for 'yes' in string (case insensitive):

示例 1,检查字符串中的 'yes'(不区分大小写):

if [[ "${str,,}" == *"yes"* ]] ;then

Example 2, check for 'yes' in string (case insensitive):

示例 2,检查字符串中的 'yes'(不区分大小写):

if [[ "$(echo "$str" | tr '[:upper:]' '[:lower:]')" == *"yes"* ]] ;then

Example 3, check for 'yes' in string (case sensitive):

示例 3,检查字符串中的 'yes'(区分大小写):

 if [[ "${str}" == *"yes"* ]] ;then

Example 4, check for 'yes' in string (case sensitive):

示例 4,检查字符串中的 'yes'(区分大小写):

 if [[ "${str}" =~ "yes" ]] ;then

Example 5, exact match (case sensitive):

示例 5,完全匹配(区分大小写):

 if [[ "${str}" == "yes" ]] ;then

Example 6, exact match (case insensitive):

示例 6,完全匹配(不区分大小写):

 if [[ "${str,,}" == "yes" ]] ;then

Example 7, exact match:

例7,完全匹配:

 if [ "$a" = "$b" ] ;then

回答by jzrk

I would suggest:

我会建议:

#!/bin/bash

s1="hi"
s2="hi"

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

Without the double quotes and with only one equals.

没有双引号,只有一个equals

回答by does_it_matter

This question has already great answers, but here it appears that there is a slight confusion between using single equal and double equals in

这个问题已经有了很好的答案,但在这里似乎在使用单等号和双等号之间存在轻微的混淆

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

The main difference lies in which scripting language you are using. If you are using Bash then include #!/bin/bashin the starting of the script and save your script as filename.bash. To execute, use bash filename.bash- then you have to use ==.

主要区别在于您使用的脚本语言。如果您使用的是 Bash,则#!/bin/bash在脚本的开头包含并保存您的脚本为filename.bash. 要执行,请使用bash filename.bash- 然后您必须使用==.

If you are using shthen use #!/bin/shand save your script as filename.sh. To execute use sh filename.sh- then you have to use single =. Avoid intermixing them.

如果您使用的是sh,则使用#!/bin/sh脚本并将其另存为filename.sh. 要执行 use sh filename.sh- 那么你必须使用 single =。避免混合它们。

回答by qwerty

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

回答by Mrki

I don't have access to a Linux box right now, but [is actually a program (and a Bash builtin), so I think you have to put a space between [and the first parameter.

我现在无法访问 Linux 机器,但[实际上是一个程序(和内置的 Bash),所以我认为你必须[在第一个参数和第一个参数之间放置一个空格。

Also note that the string equality operator seems to be a single =.

另请注意,字符串相等运算符似乎是单个=.

回答by MikeW

This is more a clarification than an answer! Yes, the clue is in the error message:

这与其说是回答,不如说是澄清!是的,线索在错误消息中:

[hi: command not found

[嗨:找不到命令

which shows you that your "hi" has been concatenated to the "[".

这表明您的“hi”已连接到“[”。

Unlike in more traditional programming languages, in Bash, "[" is a command just like the more obvious "ls", etc. - it's not treated specially just because it's a symbol, hence the "[" and the (substituted) "$s1" which are immediately next to each other in your question, are joined (as is correct for Bash), and it then tries to find a command in that position: [hi - which is unknown to Bash.

与更传统的编程语言不同,在 Bash 中,“[”是一个命令,就像更明显的“ls”等一样 - 它不会因为它是一个符号而被特殊对待,因此“[”和(替代的)“$ s1" 在您的问题中紧挨着对方,加入(对于 Bash 是正确的),然后它会尝试在该位置找到一个命令:[hi - Bash 不知道。

In C and some other languages, the "[" would be seen as a different "character class" and would be disjoint from the following "hi".

在 C 和其他一些语言中,“[”将被视为不同的“字符类”,并且与后面的“hi”不相交。

Hence you require a space after the opening "[".

因此,您需要在开头“[”之后留一个空格。