8

私はこれができることを知っています...

if diff -q $f1 $f2
then
    echo "they're the same"
else
    echo "they're different"
fi

しかし、チェックしている条件を否定したい場合はどうすればよいでしょうか? つまり、このようなもの(明らかに機能しません)

if not diff -q $f1 $f2
then
    echo "they're different"
else
    echo "they're the same"
fi

私はこのようなことをすることができます...

diff -q $f1 $f2
if [[ $? > 0 ]]
then
    echo "they're different"
else
    echo "they're the same"
fi

前のコマンドの終了ステータスが 0 より大きいかどうかを確認するところですが、これは少しぎこちなく感じます。これを行うためのより慣用的な方法はありますか?

4

3 に答える 3

13
if ! diff -q "$f1" "$f2"; then ...
于 2013-02-25T17:45:38.343 に答える
2

否定したい場合は、次を探しています!

if ! diff -q $f1 $f2; then
    echo "they're different"
else
    echo "they're the same"
fi

または (単純に if/else アクションを逆にします):

if diff -q $f1 $f2; then
    echo "they're the same"
else
    echo "they're different"
fi

または、次を使用してこれを試してくださいcmp

if cmp &>/dev/null $f1 $f2; then
    echo "$f1 $f2 are the same"
else
    echo >&2 "$f1 $f2 are NOT the same"
fi
于 2013-02-25T17:44:59.733 に答える
0

使用を否定するif ! diff -q $f1 $f2;。で文書化man test:

! EXPRESSION
      EXPRESSION is false

両方のケースを処理するため、否定が必要な理由がよくわかりません...それらが一致しないケースのみを処理する必要がある場合:

diff -q $f1 $f2 || echo "they're different"
于 2013-02-25T17:50:39.410 に答える