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.
#!/bin/bash# your code goes here seq 1 2 19
Output:
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.
#!/bin/bash# your code goes here echo $(seq 1 2 19)
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