bashcmp

Bash: return code in if statement causes unexpected behavior


I'm using the using the cmp command to check if two files are identical. I would like to stick the command into a one line if statement but it's not working as expected. When comparing two files and one the files doesn't exist, cmp returns 2. Since 2 is non-zero, I would expect the if statement to evaluate to true, but it does not and I don't understand why.

I want to write something like:

if cmp -s tickets.txt tickets_orig.txt; then
  #do stuff here
fi

because I find it short, sweet and more intuitive. Is this possible?

I was able to create a workaround by using $?, but I don't understand why the code below will evaluate to true and the code above will evaluate to false when the command returns 2:

cmp -s tickets.txt tickets_orig.txt
if [ $? -ne 0 ]; then
  #do stuff here
fi

Solution

  • Exit status ($?) = 0 means success in shell logic, it allows to define different error codes 1 to 127 for anormal status

    if command; then #...
    

    is equivalent to

    command;
    if [ $? -eq 0 ]; then #...
    

    and

    command;
    if [ $? -ne 0 ]; then #...
    

    equivalent to

    if ! command; then #...