Here Doc
When shell encounters the syntax << delimiter, it starts creating a multi-line buffer using these rules:
A line containing exactly
delimiterends the contentsEscape sequences are expanded (e.g.,
\tmay be translated into a literalTAB)Variables are expanded (e.g.,
$foobecomes contents offoovariable)Command substitutions are performed (e.g.,
$(date)and`date`become the output ofdatecommand)
The buffer created is sent as stdin to the program of your choice. For example:
1 #!/bin/sh
2 person=Jane
3 cat << EOF
4 I heard from $person that "$(date +%Y) is the year of ...," but I am doubtful.
5 EOFProduces:
I heard from Jane that "2017 is the year of ...," but I am doubtful.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:
1 #!/bin/sh
2 where="room 402"
3 what=package
4 contents="supplies for tonight's event"
5 echo "$( cat << EOF
6 $( date +"[%F %T]" ) There's a "$what" for $room containing "$contents."
7 EOF
8 )"Produces:
[2017-11-22 10:13:39] There's a "package" for room 402 containing "supplies for tonight's event."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
Was this helpful?