Bash "not": invert command exit status

I know I can do this ...

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

But what if I want to deny the condition that I am checking? i.e. something like this (which obviously doesn't work)

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

I could do something like this ...

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

Where I check if the exit status of the previous command exceeds 0. But this is a bit inconvenient. Is there a more idiomatic way to do this?

+5
source share
3 answers
if ! diff -q $f1 $f2; then ...
+8
source

If you want to deny, you are looking for !:

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

or (just change if / else actions):

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

Or try to do this with cmp:

if cmp &>/dev/null $f1 $f2; then
    echo "$f1 $f2 are the same"
else
    echo >&2 "$f1 $f2 are NOT the same"
fi
+1
source

if ! diff -q $f1 $f2;. man test:

! EXPRESSION
      EXPRESSION is false

, , ... , :

diff -q $f1 $f2 || echo "they're different"
+1

All Articles