1)
% expr "1==1"
1
Run Code Online (Sandbox Code Playgroud)
2)
% expr "i==i"
invalid bareword "i"
in expression "i==i";
should be "$i" or "{i}" or "i(...)" or ...
Run Code Online (Sandbox Code Playgroud)
为什么在步骤2中出现此错误
1) % if {"i" == "i"} {
puts "hai"
}
hai
2) % if {i == "i"} {
puts "hai"
}
invalid bareword "i"
in expression "i == "i"";
should be "$i" or "{i}" or "i(...)" or ...
Run Code Online (Sandbox Code Playgroud)
if {"i"=="i"}这是if条件的wotking.
在这里,我发现像expr命令只评估整数,而不是比较字符串,但In"if"条件的一切(整数和字符串)正在评估.
事情在这里如何运作?
答案在expr手册页中.
Operands may be specified in any of the following ways:
...
[4] As a string enclosed in double-quotes. The expression parser
will perform backslash, variable, and command substitutions on
the information between the quotes, and use the resulting value
as the operand
[5] As a string enclosed in braces. The characters between the open
brace and matching close brace will be used as the operand with?
out any substitutions.
...
Run Code Online (Sandbox Code Playgroud)
因此,expr可以比较字符串,但您必须将它们用双引号或大括号括起来,具体取决于您是否要执行替换.
因此,在您的示例2中,您必须使用
% expr {"i" == "i"}
Run Code Online (Sandbox Code Playgroud)
要么
% expr {{i} == {i}}
Run Code Online (Sandbox Code Playgroud)
更好地使用字符串比较操作数:
% expr {"i" eq "i"}
% expr {{i} eq {i}}
Run Code Online (Sandbox Code Playgroud)
确保字符串的内容未转换为数值.