Here Doc
When shell encounters the syntax << delimiter, it starts creating a multi-line buffer using these rules:
  1. 1.
    A line containing exactly delimiter ends the contents
  2. 2.
    Escape sequences are expanded (e.g., \t may be translated into a literal TAB)
  3. 3.
    Variables are expanded (e.g., $foo becomes contents of foo variable)
  4. 4.
    Command substitutions are performed (e.g., $(date) and `date` become the output of date command)
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 EOF
Produces:
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:
  1. 1.
    Double-quoted to prevent interpolation of the contents
  2. 2.
    The result of expanding a sub-shell
    1. 1.
      Running cat
      1. 1.
        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.
Copy link