8 Practical Examples of Chaining Commands in Bash Scripts

In the realm of the command line interface, efficiency is essential. Bash programmers use various kinds of commands. By harnessing the capabilities of Bash, users can combine multiple commands into a single line, revolutionizing their workflow. In this article, I will explore the art of Bash chain commands, showcasing their time-saving potential and elevating command-line proficiency.

Chaining Operators in Linux

There are some commonly used chaining operators the programmer frequently uses. I have listed some of them below:

Chaining Operator Description
& – Ampersand This operator sends a command, script, or process to the background. It makes a command run in the background.
&& –  Logical AND The && operator will only execute the second command when the first command SUCCEEDS! If the first command is not successful, then it will not execute the second command.
|| – Logical OR This is like an else statement in programming. The || will only execute the second command if the first command fails.
; – Semi-colon The command following this operator will execute even if the command preceding this operator is not successfully executed.
! – Not The NOT is like the except statement. It will run all the commands except a given condition. It negates an expression within a command.
&& – || – AND – OR This is a combination of the AND-OR operator. It is like the if-else statement in programming.
| – Pipe The output of the command preceding this operator will act as an input of the command succeeding this operator.
>, >>, < – Input – Output Redirection Redirects the output of a command or a group of commands to a file or redirects a file as input to a command.
\ – Concatenation It concatenates large commands over several lines in the shell.
() – Precedence This allows the commands to execute in precedence order.
{} – Combination The execution of the command succeeding this operator will depend on the execution of the first command.

Practical Examples of Chaining Commands in Bash

In this section, I have listed some commands which are frequently used for chaining operations in Bash. By going through this list, you will be familiar with these commands.

Example 01: Exit Status Code

When a command is successfully executed, it returns a non-zero exit status. The $? symbol stores the exit status. If a command is successfully executed, the exit status will be zero. Here, I tried to connect to the idontexist.net website. But the website is unavailable. So it has returned non-zero exit status. Then I tried to connect to youtube.com. It has successfully connected to it and returned a zero exit status. I have printed the exit status by executing the echo $? command.

Execute the following command to do the same:

ping -c 1 idontexist.net
EXPLANATION
  • ping: Initiates ping operation.
  • -c 1: Specifies the number of ping requests to send to the host. Here, one ping packet is sent.
  • idontexist.net: The IP address that will be pinged.

The ping command tries to connect to the website. When it is successful, it returns a zero exit status which has been printed subsequently.The image shows that the ping request has been executed successfully and returned a zero status.

Example 02: Logical “AND (&&)” Operator

The second command executes when the first command is executed successfully. In this example, I have passed the ping command and wget command with the logical AND (&&) operator. At first, linuxsimply.com will be accessed by the ping command, and then the wget command will download the index.html. If accessing the linuxsimply.com is unsuccessful and does not return any zero exit status, then the second command, the wget command, will not be executed.

Copy the following command to do the same:

ping -c 1 linuxsimply.com && wget linuxsimply.com
EXPLANATION
  • ping: Initiates ping operation.
  • -c 1: Specifies the number of ping requests to send to the host. Here, one ping packet is sent.
  • net: The IP address that will be pinged.
  • wget: Downloads the index file from the host website.
  • linuxsimply.com: The IP address that will be accessed for download.

At first, linuxsimply.com has been accessed by the ping command then the wget command has downloaded the index.html.The above image shows that the linuxsimply.com website is accessed successfully then the index file is downloaded.

Example 03: Logical “OR (||)” Operator

There are two commands before and after the logical OR(||) operator. The second command will only be executed when the first command is not executed successfully and returns a non-zero exit status. In this example, I have put the ls my_folder command before the OR operator. As the my_folder does not exist, it will return a non-zero exit status. And so, the second command mkdir my_folder, will be executed, and it will return a zero exit status finally, the ls command will be executed, which will print the contents of the current directory.

Use the following command to do the same:

ls my_folder || mkdir my_folder && ls
EXPLANATION
  • ls: Prints the files and folders inside the mentioned directory.
  • my_folder: Directory name.
  • ||: Logic OR operator.
  • mkdir: Creates a folder.
  • &&: Logic AND operation.

The mkdir my_folder command has been executed as my_folder is missing, and it has returned a zero exit status. Finally, the ls command has been executed, which has printed the contents of the current directory.The above image shows that the mkdir and ls commands have been executed with the help of logic OR and AND operations.

Example 04: Semicolon (;) Operator

The semicolon Operator denotes the end of a command. It will start the command following the semicolon. In this example, I have sequentially put the pwd command, the ls command, the whoami command, the who command, and the id command. These commands have been executed sequentially, as shown in the image below.

Execute the following command to do the same:

pwd; ls; whoami; who; id
EXPLANATION
  • pwd: Prints the current working directory.
  • ls: Prints the files and folders inside the current directory.
  • whoami: Displays the username of the effective user in the current shell.
  • who: Displays the username who are currently logged in.
  • id: Displayed information about users’ IDs and names.

The the pwd command, the ls command, the whoami command, the who command, and the id command commands have been executed sequentially.

The pwd command, the ls command, the whoami command, the who command, and the id command have correctly printed the information.

Example 05: “NOT (!)” Negation Operator

The NOT negation operator is like the except operator. It will execute all the commands except those specified after the negation operator. In this example, I have put the file1.txt file name after the NOT negation operation as the argument of the rm command. It will delete all the files except the file1.txt file, as seen in the image below.

Run the following command to do the same:

rm -rf !(file1.txt)
EXPLANATION
  • rm: Removes file.
  • -rf: This means recursive and force option. It removes the file recursively and forcefully.
  • !(file1.txt): This means every file will be deleted except file1.txt. Here ! is called not operator. This symbol plays the main role.

I have put the file1.txt file name after the NOT negation operation as the argument of the rm command. It has deleted all the files except the file1.txt file.The rm command has deleted all the files except the file kept after the not operator.

Example 06: Piping (|) Operator

The pipe command passes the output of the first command as input for the second command. In this example, I have passed the output of the cat file1.txt file as input of the wc -lc command.

Use the following command to do the same:

cat file1.txt | wc -lc
EXPLANATION
  • cat: Displays the contents of a file on the terminal.
  • file1.txt: File name which will be displayed on the terminal.
  • |: It is called a pipe operator. It passes the output of the first command to the second command.
  • wc: Counts the word of a file.
  • -c: This option specifies to count only the character inside a file.

The output of the cat file1.txt file has been passed as input of the wc -lc command.The above image shows that the wc command with -lc argument has printed the total line number and character numbers of the file1.txt file.

Example 07: Concatenation (\) Operator

The concatenation \ operator is an excellent tool for concatenating large commands over several lines. In this example, I have concatenated a large file name, as shown below.

Copy the following command to do the same:

touch this\ file\ with\ space.txt
EXPLANATION
  • touch: It updates the modification time.
  • this\ file\ with\ space.txt : This is the file name. Here \ will be omitted.

A large file name has been concatenated using \.The concatenation operator (\) has concatenated a file name that contains space in the name.

Example 08: Input Output Redirection (‘<‘,’>’,’>>’) Operators

You can easily redirect output to a file and take input from a file. In this example, I have executed the echo “Welcome Here!” > file2.txt . Here the output of the echo command will be redirected to the file2.txt file, as the below image shows.

Execute the following command to do the same:

echo “Welcome Here!” > file2.txt
EXPLANATION
  • echo: It prints a string on the terminal.
  • “Welcome Here!”: This message will be printed.
  • > : It redirects the output of a command to a file.
  • file2.txt: Filename where the output of the previous command will be saved.

The output of the echo command has been redirected to the file2.txt file.The output of the echo command has been passed to the file2.txt file.

Conclusion

In conclusion, mastering Bash chain commands offers efficiency, automation, and customization in command line interfaces. Proceed cautiously, but embrace the power to streamline tasks and unlock a more productive workflow.

People Also Ask

How do you chain commands in a terminal?

You can successfully chain multiple commands in a terminal using the semicolon ; operator. It does not depend on whether the previous commands were successful in executing the immediate next one.

How does a bash script work?

A file containing a series of commands that the bash programs execute line by line is known as a bash script. It enables you to carry out a number of tasks, including utilizing the command line to begin a process, create a folder, and go to a certain path.

What is a pipe in bash?

In Bash, a pipe is an operator that passes the standard input from one process as the standard output of another. Positional parameters that can be entered on the command line are supported by Bash scripts.

Is Bash a shell script?

Yes, Bash is a command processor that typically runs in a text window where the user types commands and it is also a scripting language. Automating processes using a set of commands is known as shell scripting. One kind of shell script is the bash script. Among the shells are Korn, C shell, Bourne, Bash, etc.

Related Articles


<< Go Back to Writing Bash Script | Bash Scripting Basics | Bash Scripting Tutorial

Rate this post
LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now
Susmit Das Gupta

Hello everyone. I am Susmit Das Gupta, currently working as a Linux Content Developer Executive at SOFTEKO. I am a Mechanical Engineering graduate from Bangladesh University of Engineering and Technology. Besides my routine works, I find interest in going through new things, exploring new places, and capturing landscapes. Read Full Bio

Leave a Comment