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.
cmp
it is slightly different: 0 means no difference between the two inputs, and 1 means that there is a difference, exit codes > 1 are errors. In my case, I want to check for difference in files with cmp. (Which can be done in many ways, but I think it is easiest to use cmp). So, I don't want my script to fail when it is sometimes expected that there is a difference between two files. – Niklas Rosencrantz Nov 20 '22 at 12:07cmp
does? Are you usingset -e
? Don't do that. – Charles Duffy Nov 20 '22 at 14:52if
having a nonzero exit status,if
would be useless. Consequently,set -e
ignores the exit status of "checked" commands -- which is to say, roughly, commands whose exit status is used for branching purposes. Unfortunately, the full definition is deeply nuanced and unintuitive, which is part of whyset -e
is such a bad idea, as gone into in more detail in the FAQ linked above. (I linked to just the exercises section, but the parable above it describes whyset -e
behavior came to be so hard to predict or understand). – Charles Duffy Nov 20 '22 at 14:53