私はanswering a questionだったと
if [ $(command) ]; then ...
は常に
if command; then ...
と同等であると仮定しかし、私はa couple of counter examplesを得た:
$ [ $(true) ] && echo "yes" || echo "no"
no
$ if true; then echo "yes"; else echo "no"; fi
yes
そして:
$ if echo "$xxxx"; then echo "yes"; else echo "no"; fi
yes
$ [ $(echo "$xxx") ] && echo "yes" || echo "no"
no
何も返さない、両方のケースで問題がtrue
とecho $xxxx
(未設定の変数)にあり、そのリターンコードが0であり、したがって、if
条件がTrueに評価されてecho $xxxx
が成功したのに対し、そう[ ]
は、(by definition in man test
)Falseに評価されます。
しかし、私は疑問に思っています。いつ両方のチェックが同等であると仮定できるでしょうか?これは想定するのが危険なことか、ほとんどの場合信頼性がありますか?
'[$(command)]'の場合はそれよりも悪いです。出力が1つの単語(引用符で囲まれていない場合)と出力が '['/'test'の引数のように見えない場合にのみ、確実に動作します。 '[$(printf - 'a = a')];を比較してください。 echo $? 'を' [$(printf - 'a = b')]に変換します。エコー$? 'などです。 –