Here Document

A "here document" is a Bourne shell syntactic feature that allows you to feed data to a program without storing it in an external file. It works equally well in POSIX, Korn and Bash shells too.

The basic form is:

somecommand <<WORD
your data
go
here
WORD

Here, somecommand can be any program that reads from standard input (cat is by far the most common), and WORD can be any delimiter word you like. (EOF is a common choice.)

Here documents of this form have certain characteristics:

If we want to avoid shell substitutions, we can quote the delimiter word:

somecommand <<'WORD'
your data
$go
`here`
WORD

If we want for the body of the here document to be indented like the rest of the script while also having bash remove all leading tab characters during execution, we can add a - (hyphen) suffix to the immediate right of the '<<'. Command substitutions and parameters do not need to be quoted in a here document; the quotes will be printed surrounding the processed expansion, so in this case, putting parameters in single quotes is okay. An empty space to the left of (either instance of) WORD is optional, but there may be no trailing blanks after the second delimiter.

if ...
    while ....
        somecommand <<- WORD
         this is
          an indented
           here document
        WORD
    done
fi

In this form, all leading tab characters (not spaces!) will be removed. There is no provision for removing leading spaces, or leading tabs-and-spaces. (Recall the syntactic restrictions of Makefiles, and you'll be OK.)

Here documents are typically implemented by creating a temporary file and redirecting standard input from this file when the program is invoked.

Here Strings

In bash, there is a variant of the here document called the here string. It's more compact, but also more limited:

read -a octets <<< "$ipaddr"

The <<< serves a role similar to that of the << in a here document, but there is no sentinel word to tell us where the input ends. Rather, the <<< is followed by a single word (Quotes are your friend!). That word, plus a newline, become the standard input of the command.


CategoryShell

HereDocument (last edited 2020-04-24 02:48:22 by unn-212-102-36-1)