[EnglishFrontPage] [TitleIndex] [WordIndex

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:

someprogram <<WORD
your data

Here, someprogram 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:

someprogram <<'WORD'
your data

If we want to be able to indent the here document, we can prefix the delimiter word with a - (hyphen):

if ...
    while ....
        someprogram <<-WORD
        this is
        an indented
        here document

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.


2012-07-01 04:09