为什么ksh中的以下IF条件总是评估为true? [英] Why does the following IF condition in ksh always evaluate to true?

查看:690
本文介绍了为什么ksh中的以下IF条件总是评估为true?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Consider, below code works as expected:

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

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

But when I remove the space surrounding the equality operator it always evaluates to 0 exit status (At least that's what I assume it must be returning as it is taken as true):

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






更新:

只是为了确认问题是否与等号运算符有关:

Just to confirm whether the issue lies with the equality operator or not:

#!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. 一定要注意你的空间。

  1. Using = is the same as == above, but is obsolete.
  2. ALWAYS mind your spaces.


推荐答案

来自 ksh(1)


条件表达式。

Conditional Expressions.

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

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

Now consider your second example:

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

假设 $ SOME_VARIABLE 是SOMETHINGNOTTRUE ,这扩展为:

Assuming $SOME_VARIABLE is "SOMETHINGNOTTRUE", this expands to:

if [[ SOMETHINGNOTTRUE=TRUE ]]; then

SOMETHINGNOTTRUE = TRUE是一个非零长度的字符串。因此确实如此。

"SOMETHINGNOTTRUE=TRUE" is a non-zero length string. It is therefore true.

如果你想在 [[]中使用运算符,你必须在它们周围加上空格在文档中给出(注意空格):

If you want to use operators inside of [[, you must put spaces around them as given in the docs (note the spaces):

   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.

这篇关于为什么ksh中的以下IF条件总是评估为true?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆