如何在Bash Linux中比较字符串?

as We generally use bash in order to execute commands. But as bash is a programming environment we have other programming related features. We can compare strings where these strings are output or error of some commands. In this tutorial we will look different use cases for string comparison in Bash Linux.

因为我们通常使用bash来执行命令。 但是由于bash是一种编程环境,因此我们还有其他与编程相关的功能。 我们可以比较输出这些字符串或某些命令错误的字符串。 在本教程中,我们将介绍Bash Linux中用于字符串比较的不同用例。

与平等比较 (Compare with Equality)

The most used examples for string comparison is comparing equality. We can compare two strings character by character for equality and then return some value or string according to the result. In this example we will check two string variables $s1 $s2 and return result as string like  EQUAL or NOTEQUAL. We will use == for string equality check. -eq will not work because it is only used with numbers or integers.

字符串比较最常用的示例是比较相等性。 我们可以逐字符比较两个字符串是否相等,然后根据结果返回一些值或字符串。 在此示例中,我们将检查两个字符串变量$s1 $s2并以字符串形式返回结果,例如EQUALNOTEQUAL 。 我们将使用==进行字符串相等性检查。 -eq将不起作用,因为它仅与数字或整数一起使用。

s1='poftut'
s2='poftut'
if [ "$s1" == "$s2" ] ; then echo "EQUAL"; fi
Compare with Equality
Compare with Equality
与平等比较

比较不等于(Compare For Not Equal)

We can use not logic for inequality this is useful like password check. We will check stored password and provided password.We can will use !=as inequality operator.

我们not对不等式使用not逻辑,这很有用,例如密码检查。 我们将检查存储的密码和提供的密码。我们可以使用!=作为不等式运算符。

password="secret"
read provided_password

if [ "$password" != "$provided_password" ] ; then echo "Wrong Password"; fi
Compare For Not Equal
Compare For Not Equal
比较不等于

As we can see provided password is different from secret and we print Wrong Password to the screen.

如我们所见,提供的密码不同于secret ,我们在屏幕上打印了Wrong Password

比较不区分大小写 (Compare Case-Insenstive)

While comparing strings case sensitivity is important factor. The default behavior is comparing strings in case sensitive but in some cases we may need to compare them case-insensitive. We can use bash provided nocasematch feature. This feature will disable case sensitivity for bash completely.

比较字符串时,区分大小写是重要的因素。 默认行为是比较字符串是否区分大小写,但是在某些情况下,我们可能需要比较不区分大小写的字符串。 我们可以使用bash提供的nocasematch功能。 此功能将完全禁用bash的区分大小写。

shopt -s nocasematch
s1='poftut'
s2='PoftuT'
[[ "$s1" == "$s2" ]] && echo "EQUAL" || echo "NOT EQUAL"
Compare Case-Insenstive
Compare Case-Insenstive
比较不区分大小写
LEARN MORE  How To Linux Bash For Loop In Files?
了解更多信息如何在Linux Bash中循环文件?

翻译自: https://www.poftut.com/compare-string-bash-linux/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值