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
#!/bin/bashvariable1=$(echo ‘Full form of gfg is’ )variable2=$(echo ‘GeekforGeeks’)echo “$variable1 : $variable2”
Run the script
./main.sh
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 |
Contact Us