2012-12-19 151 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) –

相關問題