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
并以字符串形式返回结果,例如EQUAL
或NOTEQUAL
。 我们将使用==
进行字符串相等性检查。 -eq
将不起作用,因为它仅与数字或整数一起使用。
s1='poftut'
s2='poftut'
if [ "$s1" == "$s2" ] ; then echo "EQUAL"; fi

比较不等于(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

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"
