Bash Command Substitution: Difference between revisions
Jump to navigation
Jump to search
No edit summary |
No edit summary |
||
Line 15: | Line 15: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
Command substitution allows the output of | Command substitution allows the output of a command or [[Bash_Functions#Returning_Values|function]] to replace the command or function itself. | ||
The command is executed in a subshell environment, and the stdout of the command | The command is executed in a subshell environment, and the stdout of the command, which would normally be sent to stdout of the executing shell, is used to replace the command. The output can be saved into a variable as follows: | ||
<syntaxhighlight lang="bash"> | <syntaxhighlight lang="bash"> | ||
Line 26: | Line 23: | ||
content=$(ps -ef) | content=$(ps -ef) | ||
</syntaxhighlight> | </syntaxhighlight> | ||
The stdout is processed as follows: Any trailing newlines are deleted. Embedded newlines are not deleted, <font color=darkgray>but they may be removed during word splitting</font>. If the substitution appears within double quotes, word splitting and filename expansion are not performed on the results. | |||
=Special Cases= | =Special Cases= |
Revision as of 18:47, 3 October 2019
Internal
Overview
Command substitution is invoked with:
$(command)
An equivalent, older and obsolete style is:
`command`
Command substitution allows the output of a command or function to replace the command or function itself.
The command is executed in a subshell environment, and the stdout of the command, which would normally be sent to stdout of the executing shell, is used to replace the command. The output can be saved into a variable as follows:
local content
content=$(ps -ef)
The stdout is processed as follows: Any trailing newlines are deleted. Embedded newlines are not deleted, but they may be removed during word splitting. If the substitution appears within double quotes, word splitting and filename expansion are not performed on the results.
Special Cases
Command substitution:
$(cat file)
can be replaced with the faster:
$(< file)