2
bash-3.2$ echo foo > foo.txt
bash-3.2$ if cmp foo.txt foo.txt; then echo EQUAL; fi
EQUAL
bash-3.2$ echo bar > bar.txt
bash-3.2$ if cmp foo.txt bar.txt; then echo EQUAL; fi
foo.txt bar.txt differ: char 1, line 1

But cmp returns 0 for equal, returns 1 for different, is the explanation that the if statement in bash is executed for a return value of 0, or what is it?

Kusalananda
  • 333,661

1 Answers1

8

Yes. In bash (and other shells), a command that exits with status 0 is considered "success", and any other exit status is considered "failure".

The bash if command doesn't strictly work with a "conditional" expression. The syntax is:

$ help if
if: if COMMANDS; then COMMANDS; [ elif COMMANDS; then COMMANDS; ]... [ else COMMANDS; ] fi
    Execute commands based on conditional.
The `if COMMANDS' list is executed.  If its exit status is zero, then the
`then COMMANDS' list is executed.  Otherwise ...

It branches based on the exit status of the COMMANDS it's given.

The typical commands you see most commonly in an if statement are the [ builtin command and the [[...]] construct. These commands work just the same way: exit with status 0 for "success/true" or non-zero for "failure/false" and, like cmp or any other command, can be used just as well inside or outside if/while/until statements.

glenn jackman
  • 85,964
  • 3
    May be worth spelling out the reason why shells consider 0 true and non-zero false (opposite to most programming languages, boolean logic, &c): it allows many different types of failure (from being unable to find a file, or running out of disk space or memory, or the process being killed, or lack of necessary permissions…). Since there's only one type of success, it makes sense to make that zero, and use non-zero status codes for the various types of failure. – gidds Nov 19 '22 at 13:38