且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-01-19 21:15:13

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

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" ]]