Bash - 条件文のgrepの問題

Bash - 条件文のgrepの問題

このコードは正しく動作しますが、同じ条件の他のバージョンでは動作しないのはなぜですか?

if grep -q string file; then
    echo found
else
    echo not found
fi

これはうまくいきません:

if [ ! `grep -q string file` ]; then
    echo not found
else
    echo found
fi

ベストアンサー1

`grep -q string file`、バックティック(または$(...)どちらが良いですか?) は次に置き換えられます。出力grep。使用されたので空の-q文字列になります。

テストを無効にするには、!テストの前に次を挿入します。

if ! grep -q pattern file; then
    echo not found
else
    echo found
fi

本当に探したいならひも(正規表現の代わりに)-Fwithも使用する必要があります。grep

おすすめ記事