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
#!/bin/bash# your code goes here seq 2 2 20
Run the script
./main.sh
Output:
We can use the output of the above command as a new command. Consider the below script,
Example:
#!/bin/bash# your code goes here echo $(seq 2 2 20)
Output:
Bash Script – Command Substitution
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 “w3wiki” and then substituted the value of the string str (“w3wiki”) 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
#!/bin/sh str=’w3wiki’echo -e “str: $str”
Run the script
./mystript.sh
Output:
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 |