如何在 Bash 的“if"语句中比较两个字符串变量? [英] How do I compare two string variables in an 'if' statement in Bash?

查看:22
本文介绍了如何在 Bash 的“if"语句中比较两个字符串变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试让 if 语句在 Bash(使用 Ubuntu):

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

#!/bin/bash

s1="hi"
s2="hi"

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

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

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:

[嗨:找不到命令

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

I've looked at various sites and tutorials and copied those, but it doesn't work - what am I doing wrong?

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

Eventually, I want to say if $s1 contains $s2, so how can I do that?

我只是算出了空格...:/我怎么说包含?

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

我试过了

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

但是没有用.

推荐答案

对于字符串相等比较,使用:

For string equality comparison, use:

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

对于字符串不等于比较,使用:

For string does NOT equal comparison, use:

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

对于a包含b,使用:

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

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

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

不好:

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

好:

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

这篇关于如何在 Bash 的“if"语句中比较两个字符串变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆