2

以下のコードが期待どおりに機能することを考慮してください。

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

しかし、等値演算子を囲むスペースを削除すると、常に 0 の終了ステータスと評価されます (少なくとも、true と見なされるため、返される必要があると想定しています)。

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. 常にあなたのスペースを気にしてください。
4

3 に答える 3

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.

   ...

したがって、次の式は真です。

[[ somestring ]]

次に、2 番目の例を考えてみましょう。

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.
于 2012-12-19T15:15:41.783 に答える
2

文字列が空の文字列でない場合、テストの 1 つの引数形式は true になるためです。唯一の引数がそれで終わるので、=TRUE確かに空の文字列ではないので、テストは true と評価されます。

宇宙、最後のフロンティア :-)

常にスペースに注意を払い、単語の分割に注意してください。

于 2012-12-19T15:18:56.043 に答える