Differences between revisions 4 and 5
Revision 4 as of 2013-06-07 04:56:09
Size: 1992
Editor: JariAalto
Comment: (all): Change occurrances of "someprogram" with more generic shell parlance "command"
Revision 5 as of 2013-06-07 04:57:44
Size: 2015
Editor: JariAalto
Comment: (Here Document): Add heading 1, to match other heading "Here Strings"
Deletions are marked like this. Additions are marked like this.
Line 1: Line 1:
== Here Document ==

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:

command <<WORD
your data
go
here
WORD

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

  • Shell substitutions (such as $variable) in the here document are performed.

  • The delimiter word must appear on a line by itself, in the first column.
  • Any whitespace in the here document is preserved, including leading whitespace.

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

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

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

if ...
    while ....
        command <<-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)