0
0
Linux CLIscripting~5 mins

Command chaining (&&, ||, ;) in Linux CLI - Commands & Configuration

Choose your learning style9 modes available
Introduction
Sometimes you want to run several commands one after another in the terminal. Command chaining lets you connect commands so they run in order, depending on whether the previous command worked or not. This helps you automate tasks without typing each command separately.
When you want to run a backup command only if the previous command to prepare files succeeded.
When you want to try a command and if it fails, run a different command to fix the problem.
When you want to run multiple commands one after another regardless of success or failure.
When you want to save time by running several commands in one line instead of typing them separately.
Commands
This command creates a directory named 'test_dir'. If the directory is created successfully, it prints 'Directory created'. The '&&' means the second command runs only if the first succeeds.
Terminal
mkdir test_dir && echo "Directory created"
Expected OutputExpected
Directory created
This tries to create 'test_dir'. If it fails (for example, if the directory already exists), it prints 'Failed to create directory'. The '||' means the second command runs only if the first fails.
Terminal
mkdir test_dir || echo "Failed to create directory"
Expected OutputExpected
mkdir: cannot create directory 'test_dir': File exists Failed to create directory
This runs two commands one after another no matter what. The ';' separates commands and both run regardless of success or failure.
Terminal
echo "First command"; echo "Second command"
Expected OutputExpected
First command Second command
Key Concept

If you remember nothing else from this pattern, remember: '&&' runs the next command only if the first succeeds, '||' runs the next command only if the first fails, and ';' runs commands one after another no matter what.

Common Mistakes
Using '&&' when you want the second command to run regardless of the first command's success.
The second command will not run if the first command fails, which may stop your script unexpectedly.
Use ';' to run commands sequentially regardless of success or failure.
Using '||' expecting the second command to run only if the first command succeeds.
'||' runs the second command only if the first command fails, so it behaves opposite to what is expected.
Use '&&' if you want the second command to run only on success.
Not quoting strings with spaces in chained commands.
The shell may split the string into multiple arguments causing errors.
Always quote strings with spaces, like echo "Directory created".
Summary
Use '&&' to run the next command only if the previous command succeeds.
Use '||' to run the next command only if the previous command fails.
Use ';' to run commands one after another regardless of success or failure.