Bash Command Substitution: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
No edit summary
Line 15: Line 15:
</syntaxhighlight>
</syntaxhighlight>


Command substitution allows the output of the command to replace the command itself.
The command is executed in a subshell environment, and the stdout of the command is used to replace the command, after 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.




Line 22: Line 25:
local content
local content
content=$(ps -ef)
content=$(ps -ef)
</syntaxhighlight>
=Special Cases=
Command substitution:
<syntaxhighlight lang="bash">
$(cat file)
</syntaxhighlight>
can be replaced with the faster:
<syntaxhighlight lang="bash">
$(< file)
</syntaxhighlight>
</syntaxhighlight>

Revision as of 18:45, 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 the command to replace the command itself.

The command is executed in a subshell environment, and the stdout of the command is used to replace the command, after 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.


Command substitution allows us to take the stdout output of a command or function, which would normally be sent to stdout of the executing shell, and save it as the value of a variable. To do this we place the command or the function within brackets, preceded by a $ sign.

local content
content=$(ps -ef)

Special Cases

Command substitution:

$(cat file)

can be replaced with the faster:

$(< file)