Hone

Lessons · Terminal · && and ||

Then, or else, regardless

a && b runs b only if a succeeded. a || b runs b only if a failed. a ; b runs both no matter what.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Build then run, but not if the build failed. Enter the folder, or make it if it is missing. The shell reads success and failure from exit codes.

How to think about it

Say the sentence: 'and then', 'or else', 'and also'. Each has its own symbol.

Worked example

mkdir build && echo "made it"
The folder was made, so the echo runs.
mkdir build 2>/dev/null || echo "already there"
The second mkdir fails, so the fallback runs.
false ; echo "runs anyway"
A semicolon does not care.

Your turn

Run the tests only if the build succeeded.

make  make test

The trap

Using ; where && was meant. The second step runs on the first step's failure, on bad state.

Practise && and || on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.