Chaining Commands in Linux
Last Updated :
09 Sep, 2024
Chaining commands in Linux is a powerful technique that allows you to execute multiple commands sequentially or simultaneously through the terminal. This approach resembles writing short shell scripts that can be directly executed in the terminal, enhancing the efficiency of your workflow. By using various chaining operators, you can control how commands are executed based on the success or failure of preceding commands.
Here, we will look into the different command chaining operators available in Linux, how they work, and practical examples to help you master this essential skill.
What is Command Chaining in Linux?
Command chaining in Linux involves linking multiple commands together using special operators. These operators determine the sequence and conditions under which the commands are executed. Command chaining is useful for automating tasks, simplifying scripts, and managing complex operations directly from the command line.
Common Chaining Operators in Linux
Some commonly used chaining operators are as follows:
Operators | Function |
---|
& (Ampersand) | This command sends a process/script/command to the background. |
---|
&& (Logical AND) | The command following this operator will only execute if the command preceding this operator has been successfully executed. |
---|
; (Semi-colon) | The command following this operator will execute even if the command preceding this operator is not successfully executed. |
---|
|| ( Logical OR) | The command succeeding this operator is only executed if the command preceding it has failed. |
---|
| (Pipe) | The output of the first command acts as input to the second command. |
---|
! (NOT) | Negates an expression within a command. It is much like an "except" statement. |
---|
>,>>, < (Redirection) | Redirects the output of a command or a group of commands to a file or stream. |
---|
&&-|| (AND-OR) | It is a combination of AND OR operator and is similar to the if-else statement. |
---|
\ (Concatenation) | Used to concatenate large commands over several lines in the shell. |
---|
() (Precedence) | Allows command to execute in precedence order. |
---|
{} (Combination) | The execution of the command succeeding this operator depends on the execution of the first command. |
---|
Working with chaining operators
1. Ampersand(&) Operator:
It is used to run a command in the background so that other commands can be executed. It sends a process/script/command to the background so that other commands can be executed in the foreground. It increases the effective utilization of system resources and speeds up the script execution. This is also called as Child process creation or forking in other programming languages. Ampersand sign can be used as follows:
ping -cl google.com & #change the command before &
ping -c1 google.com & ping -c1 geeksforgeeks.org &


2. AND (&&) Operator:
The command succeeding this operator will only execute if the command preceding it gets successfully executed. It is helpful when we want to execute a command if the first command has executed successfully.
echo "hello there" && echo "this is gfg"
apt update && echo "hello"

3. Semi-colon(;) Operator:
It is used to run multiple commands sequentially in a single go. But it is important to note that the commands chained by (;) operator always executes sequentially. If two commands are separated by the operator, then the second command will always execute independently of the exit status of the first command.
Unlike the ampersand operator, the execution of the second command is independent of the exit status of the first command. Even if the first command does not get successfully executed i.e, the exit status is non-zero, the second command will always execute.
who;pwd;ls

The three commands will get executed sequentially. But the execution of the command preceding ( ; ) operator will execute even if the execution of the first command is not successful.
4. Logical OR (||) Operator:
The command succeeding this operator will only execute if the execution of the command preceding it fails. It is much like an else statement. If the execution status of the first command is non-zero then the second command will get executed.
echo "hello there" || echo "This is gfg"
apt update || echo "hello"

5. Piping (|) Operator:
This operator sends the output of the first command to the input of the second command.
ls -l | wc -l
In the above command 'wc -l' displays the number of lines. 'ls -l' displays the lists the files in the system. The first command displays the number of files in the directory. 'ls - l' lists the names of the files and this output is sent to the next command which counts the number of lines in the input. As a result, by using pipe we get the number of files in the directory.

6. NOT (!) operator:
It is used to negate an expression in command/. We can use it to delete all files except one in a directory.
touch a.txt b.txt c.txt d.txt e.txt
rm -r !(a.txt)
This command will remove all files in the directory except 'a.txt'. In the image below, we create some files using the touch command inside a directory. ls shows the files in the directory. To delete all files except 'a.txt' we use '!' Operator. If we list the files again, we can see that all files except 'a.txt' are removed.

7. Redirection Operators('<','>','>>'):
This operator is used to redirect the output of a command or a group of commands to a stream or file. This operator can be used to redirect either standard input or standard output or both. Almost all commands accept input with redirection operators.
cat >>file_name
sort <file_name
The first command creates a file with the name 'file_name' (The redirection operator >> allows us to give input in the file) while the second command will sort the contents of the file. Refer to the image below, we first create a file with numbers and then use this command. This sorts the content of the files.

8. AND, OR Operators as an if-else condition:
This command can be used as an if-else statement. It is a combination of logical AND and logical OR operators.
[ ! -d ABC ] && mkdir ABC || cd ABC
This command will first check if the directory 'ABC' exists or not. If it does not exist then a new directory is created else 'ABC' becomes the current directory. Refer to the image below, the directory named 'ABC' does not exist and hence it is created. When the same command is executed the second time, then the directory already exists and hence 'ABC' becomes the current directory.

9. Concatenation Operator(\):
Used to concatenate large commands over several lines in a shell. It also improves the readability for the users. A large command is split over several lines and hence, it is used to execute large commands.
gedit text\(1\).txt
It will open a file named text(1).
10. Precedence:
This command is used to set precedent value so that multiple commands can execute in a given order.
cmd1 && cmd 2 || cmd3
( cmd1 && cmd 2 ) || cmd3
In the first case, if the first command is successful then the second will get executed but the third command will not execute. But in the second case, the third command will get executed as the precedence is set using the () operator. If the directory exists (the first command), then the current directory becomes PQR (second command) but in the first case the third command is not getting executed while in the second case when the precedence operator is used then the third command is also executed.

11. Combination Operator ({}):
The execution of the command succeeding this operator depends on the execution of the first command. The set of commands combined using {} operator executes when the command preceding it has successfully executed.
[ -f hello.txt ] && echo "file exists" ; echo "hello"
[ -f hello.txt ] && { echo "file exists" ; echo "hello"; }
In the first case, hello will always get printed. If the file exists then the command will get executed as it is preceding the && operator. If we want to execute both second and third commands only if the file exists, then we use {} operators to combine the commands.

Conclusion
Command chaining in Linux is a versatile technique that streamlines the execution of multiple commands, making complex tasks easier to manage directly from the terminal. By understanding and mastering chaining operators like '&&', '||', ';', and others, you can automate workflows, handle conditional execution, and improve your overall efficiency in a Linux environment. Whether you’re automating routine tasks, managing files, or monitoring system status, command chaining can significantly enhance your command-line productivity.
Similar Reads
Fun Commands in Linux Linux isn't just for coding and administrationâit can also be a lot of fun. With a variety of terminal commands, you can add some entertainment to your Linux experience. Below is a list of some cool and fun commands you can use in Linux to enhance your terminal experience. Weâll also cover how to in
3 min read
ls Command in Linux The ls command is one of the most used commands in the Linux terminal to display the files and directories or path in the terminal. So, using the ls command is a basic skill for navigating the Linux file system, handling files, and managing directories.What is the ls Command in LinuxThe ls command i
10 min read
Linux Commands Linux commands are essential for controlling and managing the system through the terminal. This terminal is similar to the command prompt in Windows. Itâs important to note that Linux/Unix commands are case-sensitive. These commands are used for tasks like file handling, process management, user adm
15+ min read
Linux Commands Cheat Sheet Linux, often associated with being a complex operating system primarily used by developers, may not necessarily fit that description entirely. While it can initially appear challenging for beginners, once you immerse yourself in the Linux world, you may find it difficult to return to your previous W
13 min read
Linux command in DevOps DevOps engineers use Linux every day because itâs free, fast, and easy to customize. More importantly, most DevOps tools like Docker, Kubernetes, Ansible, Terraform, and Jenkins are built to run best on Linux.In DevOps, you often work on cloud servers (like AWS, Azure, or Google Cloud), and most of
9 min read
Basic CentOS Linux Commands in linux CentOS is a free and open-source operating system that aims to provide a stable reliable, and community-supported platform for servers and other enterprise applications. In this article, we will be covering CentOS Linux basics commands and functions of CentOS and also we will look into the advanced
4 min read
batch command in Linux with Examples batch command is used to read commands from standard input or a specified file and execute them when system load levels permit i.e. when the load average drops below 1.5. Syntax: batch It is important to note that batch does not accepts any parameters. Other Similar Commands: atq: Used to display th
1 min read
apt command in linux with examples apt provides a high-level Command Line Interface (CLI) for the APT package management system, offering a user-friendly interface intended for interactive use. It simplifies common tasks like installation, upgrades, and removal, with better defaults than more specialized tools like apt-get and apt-ca
5 min read
aptitude command in Linux with examples The aptitude command in Linux provides a user-friendly interface to interact with the machine's package manager. It functions similarly to a control panel, like in Windows, allowing you to install, upgrade, and remove packages. The command can be used in either a visual interface or directly via the
4 min read
Internal and External Commands in Linux The UNIX system is command-based i.e things happen because of the commands that you key in. All UNIX commands are seldom more than four characters long. They are grouped into two categories: Internal Commands : Commands which are built into the shell. For all the shell built-in commands, execution o
4 min read