【问题标题】:Why does the following IF condition in ksh always evaluate to true?为什么 ksh 中的以下 IF 条件总是评估为真?
【发布时间】:2012-12-06 23:19:29
【问题描述】:

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

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

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

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. 时刻注意您的空间。

【问题讨论】:

标签: unix if-statement ksh


【解决方案1】:

顺便说一句,这在 ksh 手册页中明确指出(在 test 命令的描述中):

请注意,如果 test[ ... ] 的参数数量少于五个,则应用一些特殊规则(由 POSIX 提供):如果可以剥离前导 ! 参数,只有一个参数仍然 然后执行字符串长度测试(同样,即使参数是一元运算符)

(强调我的)

【讨论】:

  • 只是为像我这样的新手添加...注意:一个常见的错误是使用if [ $foo = bar ],如果参数 foo 为空或未设置,如果它具有嵌入的空格(即 IFS个字符),或者如果它是像 !-n 这样的一元运算符。请改用 if [ "X$foo" = Xbar ] 之类的测试。取自Reference ksh man page
【解决方案2】:

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

太空,最后的边疆 :-)

始终注意您的空间并牢记分词。

【讨论】:

  • 嘿,感谢@Jens 的解释! +1 评论“太空,最后的边疆..”哈哈
【解决方案3】:

来自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.

【讨论】:

  • 感谢@Rob 的解释。我期待如果需要将其作为字符串的一部分,我们需要使用运算符和转义字符。
猜你喜欢
  • 2015-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-28
  • 2018-02-24
  • 1970-01-01
  • 2018-07-01
  • 1970-01-01
相关资源
最近更新 更多