The Wayback Machine - https://web.archive.org/web/20240726092645/https://www.geeksforgeeks.org/bash-script-command-substitution/
Open In App

Bash Script – Command Substitution

Last Updated : 31 Jul, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

In order to understand command substitution, let us first discuss substitution in shell scripts. Substitution is a functionality by following which we can instruct the shell to substitute the actual value of an expression. 

Example: 

In the program below we have firstly created variable str and assigned it with the value “GeeksforGeeks” and then substituted the value of the string str (“GeeksforGeeks”) in the echo command.

Creating a script. (you can replace `mystript` with the desired name)

vim mystript.sh

Making script executable.

chmod +x mystript.sh

393

#!/bin/sh str=’GeeksforGeeks’echo -e “str: $str”

Run the script

 ./mystript.sh

Output:

394

This article focuses on the command substitution technique used in a Bash script.

There are some sequences of characters that don’t represent their true nature but they have special meaning to the operating system and these sequences are known as escape sequences. When they are used in a command, they are replaced by actual values.

Escape Sequences Significance
 \n new line
\r carriage return
\t horizontal tab
\b backspace
 \\ backslash

Command Substitution 

Command substitution is a mechanism that is followed by programmers in a bash script. In this mechanism, the output of a command replaces the command itself. Bash operates the expansion by executing a command and then replacing the command substitution with the standard output of the command. In simple words, the output of a UNIX command is bundled and then used as a command. 

To understand it in a better way, let us consider an example. The seq command in Linux is used to print numbers from START to END in steps of INCREMENT.

Syntax:

seq START INCREMENT END  

Return type:

Print numbers from START to END each in the new line by the difference of INCREMENT.

Example:

In the below script we are printing numbers from 2 to 20 with a difference of 2. In other words, we are printing even numbers up to 20.

Creating a script. (you can replace `main` with desired name)

vim main.sh

Making script executable.

chmod +x main.sh

395

#!/bin/bash# your code goes here seq 2 2 20

Run the script

 ./main.sh

Output:

396

We can use the output of the above command as a new command. Consider the below script,  

Example:

397

#!/bin/bash# your code goes here echo $(seq 2 2 20)

Output:

398

Variables and command expansion

During the process of command substitution, the output of the command can be assigned to a variable, just like any other value.

Example:

In the below script we have assigned the result of the echo command to both the strings in variables, “varaiable1” and “variable2” respectively. Then we used these variables in the echo command.

Creating a script. (you can replace `main` with desired name)

vim main.sh

Making script executable.

chmod +x main.sh

399

#!/bin/bashvariable1=$(echo ‘Full form of gfg is’ )variable2=$(echo ‘GeekforGeeks’)echo “$variable1 : $variable2”

Run the script

 ./main.sh

Output:

400

Loss of newlines in command substitution

In the command substitution mechanism, If the output of a command that is being substituted contains any trailing newlines, then in that case the trailing newlines are deleted after the substitution. Note that embedded newlines are not deleted, but they might be removed during word splitting.

Example:

In this script, we are using the seq command. Now seq command prints numbers to the console and appends a newline character after each number is printed to the console.

401

#!/bin/bash# your code goes here seq 1 2 19

Output:

402

Example:

In this script, we have used the result of the above command and substituted it in the command. As you can see in the output, numbers from 1 to 19 with the difference of 2 are printed to console. But this time they all are printed on the same line that is without any newline character.  

403

#!/bin/bash# your code goes here echo $(seq 1 2 19)

Output:

404

Conclusion

In this article we discussed Bash Script – Command Substitution which is a useful trick that helps us take the result of one command and use it in another. We can store the command’s output in a variable or use it directly in a new command. It makes your scripts more flexible and efficient, automating tasks easily. Just remember that sometimes newlines may disappear from the output, so be careful with formatting. With command substitution, our Bash scripts become more powerful and can do things quickly and effectively.



Similar Reads

Bash Script - Difference between Bash Script and Shell Script
In computer programming, a script is defined as a sequence of instructions that is executed by another program. A shell is a command-line interpreter of Linux which provides an interface between the user and the kernel system and executes a sequence of instructions called commands. A shell is capable of running a script. A script that is passed to
3 min read
Bash Scripting - Introduction to Bash and Bash Scripting
Bash is a command-line interpreter or Unix Shell and it is widely used in GNU/Linux Operating System.  It is written by Brian Jhan Fox. It is used as a default login shell for most Linux distributions. Scripting is used to automate the execution of the tasks so that humans do not need to perform them individually. Bash scripting is a great way to a
10 min read
Bash Script - Define Bash Variables and its types
Variables are an important aspect of any programming language. Without variables, you will not be able to store any required data. With the help of variables, data is stored at a particular memory address and then it can be accessed as well as modified when required. In other words, variables let you store, read, access, and manipulate data. Workin
12 min read
Bash Script - Working of Bash Variables
A Bash script is a plain text file. This file contains different commands for step-by-step execution. These commands can be written directly into the command line but from a reusability perceptive it is useful to store all of the inter-related commands for a specific task in a single file. We can use that file for executing the set of commands one
7 min read
Bash Scripting - Write Output of Bash Command into Log File
Let there are some situations in which you have to save your output in a file ( generally called log file). Output can be user details ( username, password, Gmail, etc. ), products record ( buying or selling any goods ), or simply any kind of data that you can store in a log file. Let see how to write the output of the bash command into a log file.
4 min read
Bash Scripting - Bash Echo Command
In this article, we are going to see the echo command. The Echo command is a built-in command feature for Unix / Linux which is generally used to display the text or message on the screen. Syntax : $ echo [option][text]For Example : $ echo Geeks For GeeksOutput : Geeks For Geeks There are generally three options:-n: It does not print the trailing n
2 min read
Bash shell script to find out the largest value from given command line arguments
Write a shell script to find out the largest value from the given number of command-line arguments. Example: Special variables in bash: $@- All arguments. $#- Number of arguments. $0- Filename. $1, $2, $3, $4 ... - Specific arguments. Approach If the number of arguments is 0, end the program. If not zero, then Initialize a variable maxEle with firs
1 min read
Bash Script - How to use Command Line Arguments
In this article, let us see about Command Line Arguments usage in Bash script. Arguments are inputs that are necessary to process the flow. Instead of getting input from a shell program or assigning it to the program, the arguments are passed in the execution part. Positional Parameters Command-line arguments are passed in the positional way i.e. i
4 min read
Bash Scripting - Bash Read Password without Echoing back
Generally, you can see on the login page, whenever we type a password either it show dot (â€Ē) or asterisk (*) instead of a password. They do so because to protect our system or account. In such a case, the login page read the password and in place of the password, it will show a dot or asterisk. And in some cases, a dot or asterisk also may not appe
3 min read
Bash Scripting - How to Run Bash Scripting in Terminal
In this article, we are going to see how to run bash script in terminal. For example, we create a bash file set of instructions or commands ( known as bash script ), and through command, we can run this file in terminal. Let see how to run bash script in terminal. Example 1 : In this example we print or echo some text on screen with the help of a t
2 min read
Article Tags :
three90RightbarBannerImg