Bash Here documents and here strings Limit Strings


Example

A heredoc uses the limitstring to determine when to stop consuming input. The terminating limitstring must

  • Be at the start of a line.
  • Be the only text on the line Note: If you use <<- the limitstring can be prefixed with tabs \t

Correct:

cat <<limitstring
line 1
line 2
limitstring

This will output:

line 1
line 2

Incorrect use:

cat <<limitstring
line 1
line 2
 limitstring

Since limitstring on the last line is not exactly at the start of the line, the shell will continue to wait for further input, until it sees a line that starts with limitstring and doesn't contain anything else. Only then it will stop waiting for input, and proceed to pass the here-document to the cat command.

Note that when you prefix the initial limitstring with a hyphen, any tabs at the start of the line are removed before parsing, so the data and the limit string can be indented with tabs (for ease of reading in shell scripts).

cat <<-limitstring
        line 1    has a tab each before the words line and has
            line 2 has two leading tabs
        limitstring

will produce

line 1    has a tab each before the words line and has
line 2 has two leading tabs

with the leading tabs (but not the internal tabs) removed.