I was skimming through an /etc/rc.d/init.d/sendmail file (I know this is hardly ever used, but I'm studying for an exam), and I've become a bit confused about the && and the || operators. I've read where they can be used in statements such as

if [ test1 ] && [ test2 ]; then
     echo "both tests are true"
elif [ test1 ] || [ test2 ]; then
     echo "one test is true"

This script however shows single line statements such as

[ -f /usr/sbin/sendmail ] || exit 0

These seem to be using the && and || operators to elicit responses based on tests, but I haven't been able to dig up documenation regarding this particular use of these operators. Can you explain what they are trying to achieve in this specific context?

Best Answer

The right side of && will only be evaluated if the exit status of the left side is zero (i.e. true). || is the opposite: it will evaluate the right side only if the left side exit status is non-zero (i.e. false).

You can consider [ ... ] to be a program with a return value. If the test inside evaluates true it returns zero otherwise


$ false && echo howdy!

$ true && echo howdy!
$ true || echo howdy!

$ false || echo howdy!

Extra notes:

If you do which [ , you might see that [ actually does point to a program! It's usually not actually the one that runs in scripts, though; run type [ to see what actually gets run. If you wan to try using the program, just give the full path like so: /bin/[ 1 = 1 .