In Linux, you can combine multiple commands in one line using different "operators." The one you choose depends on whether you want the commands to care about each other's success.
Here are the four most common ways to combine commands:
1. The Semicolon ( ; ) - "Run regardless"
Use this if you just want to run several commands in a row, one after another, no matter what happens.
- Syntax:
command1 ; command2 - Example:
date ; ls ; whoami - What happens: The terminal will show the date, then list files, then show your username. Even if
lsfails,whoamiwill still run.
2. The Logical AND ( && ) - "Run only if successful"
This is the most popular way to combine commands. The second command runs only if the first one succeeds (returns an exit code of 0).
- Syntax:
command1 && command2 - Example:
mkdir my_folder && cd my_folder - Why use it: You don't want to try entering the folder if the folder failed to be created!
3. The Logical OR ( || ) - "Run only if failed"
The second command runs only if the first one fails.
- Syntax:
command1 || command2 - Example:
ls missing_file || echo "File not found!" - Why use it: It's great for error handling or providing "fallback" options.
4. The Pipe ( | ) - "Pass the data"
This doesn't just run them sequentially; it connects the output of the first to the input of the second.
- Syntax:
command1 | command2 - Example:
history | tail -n 5 - What happens: It takes your command history and passes it to
tail, which filters it to show only the last 5 lines.
Pro Tip: Combining for Efficiency
You can even mix them!
mkdir backup && cp photo.jpg backup/ || echo "Backup failed!"
- Translation: "Make a backup folder. If that works, copy the photo into it. If any of that fails, tell me it failed."
Try this in your terminal right now:
echo "Hello" && echo "Combine" && echo "Success!"
Does that help clarify how to chain your commands together?