8

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 negate the condition that I'm 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 whether the exit status of the previous command is greater than 0. But this feels a bit awkward. Is there a more idiomatic way to do this?

Coquelicot
  • 8,155
  • 4
  • 31
  • 37

3 Answers3

13
if ! diff -q "$f1" "$f2"; then ...
William Pursell
  • 190,037
  • 45
  • 260
  • 285
2

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

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

or (simplty reverse the if/else actions) :

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

Or also, try doing this using cmp :

if cmp &>/dev/null $f1 $f2; then
    echo "$f1 $f2 are the same"
else
    echo >&2 "$f1 $f2 are NOT the same"
fi
Gilles Quenot
  • 154,891
  • 35
  • 213
  • 206
0

To negate use if ! diff -q $f1 $f2;. Documented in man test:

! EXPRESSION
      EXPRESSION is false

Not quite sure why you need the negation, as you handle both cases... If you only need to handle the case where they don't match:

diff -q $f1 $f2 || echo "they're different"
Karoly Horvath
  • 91,854
  • 11
  • 113
  • 173
  • 1
    Is this actually invoking test though? I'm not using "test" nor "[". – Coquelicot Feb 25 '13 at 18:00
  • 1
    It's not invoking it, it's a shell builtin (for performance reasons), but the syntax is the same – Karoly Horvath Feb 25 '13 at 18:19
  • 2
    `man test` is irrelevant here. From `man bash`: _ If the reserved word ! precedes a pipeline, the exit status of that pipeline is the logical negation of the exit status as described above._ – Pawel Veselov May 10 '18 at 17:17