Here Doc
When shell encounters the syntax << delimiter
, it starts creating a multi-line buffer using these rules:
A line containing exactly
delimiter
ends the contentsEscape sequences are expanded (e.g.,
\t
may be translated into a literalTAB
)Variables are expanded (e.g.,
$foo
becomes contents offoo
variable)Command substitutions are performed (e.g.,
$(date)
and`date`
become the output ofdate
command)
The buffer created is sent as stdin
to the program of your choice. For example:
Produces:
Like the example for double-quoted strings, except on line 4 of the above script, double-quotes do not have to be escaped. The here document syntax can sometimes be used to avoid issues with single versus double quotes when sometimes both are required. For example:
For example:
Produces:
There's a lot to unpack here. We'll go line by line.
On line 5, our only argument to echo is:
Double-quoted to prevent interpolation of the contents
The result of expanding a sub-shell
Running cat
Given a here document
Line 7 is the ending delimiter for the here document and line 8 is the end of the sub-shell and double-quote started on line 5.
Last updated