2012-12-19 69 views
2

考虑,下面的代码按预期工作:为什么ksh中的以下IF条件总是评估为真?

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 

UPDATE:

只是为了CONFI RM问题是否出在平等的经营者或不:

#!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 


[[email protected]]$ sh test.sh 
Always true. 

UPDATE:

摘要:

  1. 使用=是同上==,但已经过时了。
  2. 始终注意你的空间。
+1

=是赋值运算符,而==和===是比较运算符。 – SISYN

+0

我的观察结果是不同的。当我使用'='用空格时,它正确地作为比较运算符。 [在这里看到更多的例子](http://www.well.ox.ac.uk/~johnb/comp/unix/ksh.html#branching)。 –

+0

.. [Korn中的字符串比较](http://www.well.ox.ac.uk/~johnb/comp/unix/ksh.html#comparisons)。 –

回答

4

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. 

    ... 

所以下面的表达式为true:

[[ 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. 
+0

感谢@Rob的解释..我期待我们需要使用运算符以及转义字符,如果它需要作为字符串的一部分。 –

2

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

太空,最后边疆:-)

经常注意倾听你的空间和记住单词拆分。

+0

嘿感谢您的解释@Jens! +1,为您的评论“空间,最后的边境..”哈哈 –

+1

嘿,一个同伴trekkie :-) – Jens

0

只是堆在,这是明确的KSH手册页叫出来(在test命令的描述):

注意一些特殊的规则适用(POSIX提供)如果数量的参数test[ ... ]小于五:如果主导!参数可以被剥离,使得只有一个参数保持然后执行串长度测试(再次,即使参数是一元运算符)

(强调我的)

+0

只是为了补充这个像我这样的新手......注意:一个常见的错误是使用'if [$ foo = bar]',如果参数foo为空或未设置,嵌入空格(即IFS字符),或者是像'!'或'-n'这样的一元运算符,则失败。改用'if [“X $ foo”= Xbar]'来代替测试。摘自[参考ksh手册页](http://ccrma.stanford.edu/planetccrma/man/man1/ksh.1.html) –

相关问题