Combining Commands
; && and ||.
You can put several commands on one line. But should the second command run if the first one fails? Linux gives you three ways to join commands, depending on what you want.

- Several commands, one line
- What if one fails?
- Three ways to join them
Semicolon: one after another
A semicolon simply runs commands one after another, no matter what happens. Here, the first command fails, because the folder doesn't exist. But echo still runs anyway.
cd nowhere; echo "still runs" bash: cd: nowhere: No such file or directory still runs
And, and or
Two ampersands mean and. The second command only runs if the first one succeeded. MK dir, and then CD. Two vertical bars mean or. The second only runs if the first one failed. Here, cat fails, so the backup message appears.
mkdir reports && cd reports cat missing.txt || echo "no such file, using defaults" cat: missing.txt: No such file or directory no such file, using defaults
Which one to use
Use a semicolon when the commands don't depend on each other. Use two ampersands when the second step only makes sense if the first worked, like making a folder, then going into it. And use two bars for a plan B, when something might fail.
| Join | Runs the next command |
|---|---|
| a ; b | always |
| a && b | only if a worked |
| a || b | only if a failed |
Summary
Semicolon always runs the next command, and and only runs it on success, or or only on failure. Next, how Linux knows a command succeeded. Exit codes.
Key takeaways- a ; b always
- a && b on success
- a || b on failure