0

The script is test.sh.

#!/bin/sh

if cmp -s file.a file.b; then
  echo diff
else
  echo same
fi

When checking the exit code from cmp -s I see:

When file.a and file.b are different.

cmp -s file.a file.b
echo $?
1

When file.a and file.b are the same.

cmp -s file.a file.b
echo $?
0

Why then does the conditional statement seem to operate in the reverse?

When file.a and file.b are different.

./test.sh
same

When file.a and file.b are the same.

./test.sh
diff

This isn't the first time I've seen this. I must be misunderstanding how the if statement interprets the exit code, or maybe it isn't the exit code at all?

Appleoddity
  • 131
  • 1
  • 1
  • 7
  • Yes, the shell's "success" status is the opposite of the C boolean values. – glenn jackman Jan 07 '22 at 15:36
  • The POSIX shell reference for `if` -- https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_09_04_07 – glenn jackman Jan 07 '22 at 15:38
  • Ok. Thank you. This just seems backwards from my logic. Traditionally, I think of zero as false, and non-zero as true. – Appleoddity Jan 07 '22 at 15:40
  • 1
    Does this answer your question? [why are the definition of true and false in stdbool.h the exact opposite from the UNIX programs true and false?](https://unix.stackexchange.com/q/641098/100397) – roaima Jan 07 '22 at 16:01
  • @Appleoddity, yep, it is backwards wrt. everything else. But it always has been, and always will be. It does have the upside that programs can return multiple _different_ exit codes indicating failures – ilkkachu Jan 07 '22 at 16:15

0 Answers0