为什么ksh中的以下IF条件总是评估为真?

请考虑,下面的代码按预期工作:

if [[ $SOME_VARIABLE = "TRUE" ]]; then echo "Only echoed when \$SOME_VARIABLE stores string \"TRUE\"." fi 

但是,当我删除等于运算符周围的空间时,它总是评估为0退出状态(至less这是我认为它必须返回,因为它被视为真):

 if [[ $SOME_VARIABLE="TRUE" ]]; then echo "Always true." fi 

更新:

只是为了确认问题是否存在于平等运算符:

 #!usr/bin/ksh SOME_VARIABLE=FALSE if [[ $SOME_VARIABLE == "TRUE" ]]; then echo "Only echoed when \$SOME_VARIABLE stores string \"TRUE\"." fi if [[ $SOME_VARIABLE=="TRUE" ]]; then echo "Always true." fi [kent@TEST]$ sh test.sh Always true. 

更新:

概要:

  1. 使用=与上面的==相同,但已经过时。
  2. 始终注意你的空间。

ksh(1)

条件表达式。

  A conditional expression is used with the [[ compound command to test attributes of files and to compare strings. Field splitting and file name generation are not performed on the words between [[ and ]]. Each expression can be constructed from one or more of the following unary or binary expressions: **string** True, if string is not null. ... 

所以下面的表达式是正确的:

 [[ somestring ]] 

现在考虑你的第二个例子:

 if [[ $SOME_VARIABLE="TRUE" ]]; then 

假设$SOME_VARIABLE是“SOMETHINGNOTTRUE”,这扩展到:

 if [[ SOMETHINGNOTTRUE=TRUE ]]; then 

“SOMETHINGNOTTRUE = TRUE”是一个非零长度的字符串。 所以是真的

如果你想使用[[运算符,则必须在文档中给出空格(请注意空格):

  string == pattern True, if string matches pattern. Any part of pattern can be quoted to cause it to be matched as a string. With a successful match to a pattern, the .sh.match array variable will contain the match and sub-pattern matches. string = pattern Same as == above, but is obsolete. 

因为如果字符串不是空字符串,则测试的一个参数形式为真。 由于唯一的参数以=TRUE结尾,它肯定不是空字符串,所以测试结果为真。

空间,最后的边疆:-)

时刻关注你的空间,牢记分词。

只需要在ksh手册页(在test命令的描述中)明确地指出:

请注意,如果要test的参数数量少于五个,则应用一些特殊规则(POSIX提供):如果超前! 参数可以被剥离, 只剩下一个参数,然后执行字符串长度测试 (再次,即使参数是一元运算符)

(重点是我的)