带有 ((...)) 字符串比较的 if 语句在 bash 脚本中不起作用

Poo*_*nam 1 bash string shell-script

我写了下面的脚本:

#!/usr/bin/bash

STR_1="nfosys"
STR_2="Infosys"

if (( $STR_1 == $STR_2 ))
then
        echo "Strings are equal"
else
        echo "Strings are not equal"
fi
Run Code Online (Sandbox Code Playgroud)

获取输出:

root:~/Desktop/user_repo/Demo# bash -x test.sh 
+ STR_1=nfosys
+ STR_2=Infosys
+ ((  nfosys == Infosys  ))
+ echo 'Strings are equal'
Strings are equal
root:~/Desktop/user_repo/Demo# 
Run Code Online (Sandbox Code Playgroud)

理想情况下,它应该打印“字符串不相等”语句,但我无法理解为什么它打印“字符串相等”

ilk*_*chu 7

(( .. ))是一个算术构造,在算术上下文中,字符串被视为变量的名称,并使用该变量的值。这种情况发生在$var扩展扩展之后,因此您的脚本会查看名为nfosys和 的变量Infosys。如果两个变量均未设置,则两者均为零,即相等。但:

$ str1=foo str2=bar foo=1
$ (( $str1 == $str2 )) && echo true || echo false
false   
Run Code Online (Sandbox Code Playgroud)

例如参见Bash 的 shell 算术手册:

允许 Shell 变量作为操作数;参数扩展在计算表达式之前执行。在表达式中,shell 变量也可以通过名称引用,而不使用参数扩展语法。当通过名称引用而不使用参数扩展语法时,为 null 或未设置的 shell 变量的计算结果为 0。

对于字符串比较,请使用

[ "$STR_1" = "$STR_2" ]   # in any POSIX shell, or

[[ $STR_1 = "$STR_2" ]]   # in Bash/ksh/zsh
Run Code Online (Sandbox Code Playgroud)

前者由于分词而需要引号,后者仅在右侧(在 bash / ksh 中)需要引号,以免$STR_2被视为模式。

另请参阅:Bash 运算符 [[ vs [ vs ( vs ((?