AI Hints
Home›Linux Tutorial›Errors and Combining
Linux · Lesson 54 of 120

Combining Commands

; && and ||.

⏱ 2 min read▶ Video at 1:09:12🎓 Free
Watch this lesson in the Linux courseWatch on YouTube ↗Full Linux course

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.

Combining Commands
From the video: Combining Commands
  • 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.

Terminal
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.

Terminal
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.

JoinRuns the next command
a ; balways
a && bonly if a worked
a || bonly 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
Next up: Exit Codes — success or failure