Here Documents

Chapter 17. Here Documents

A here document uses a special form of I/O redirection to feed a command list to an interactive program or command, such as ftp, telnet, or ex. A "limit string" delineates (frames) the command list. The special symbol << designates the limit string. This has the effect of redirecting the output of a file into the program, similar to interactive-program < command-file, where command-file contains
command #1
command #2
...

The "here document" alternative looks like this:
#!/bin/bash
interactive-program <<LimitString
command #1
command #2
...
LimitString

Choose a limit string sufficiently unusual that it will not occur anywhere in the command list and confuse matters.

Note that here documents may sometimes be used to good effect with non-interactive utilities and commands.

The above script could just as effectively have been implemented with ex, rather than vi. Here documents containing a list of ex commands are common enough to form their own category, known as ex scripts.

The - option to mark a here document limit string (<<-LimitString) suppresses tabs (but not spaces) in the output. This may be useful in making a script more readable.

A here document supports parameter and command substitution. It is therefore possible to pass different parameters to the body of the here document, changing its output accordingly.

Quoting or escaping the "limit string" at the head of a here document disables parameter substitution within its body. This has very limited usefulness.

This is a useful script containing a here document with parameter substitution.

A here document can supply input to a function in the same script.

It is possible to use : as a dummy command accepting output from a here document. This, in effect, creates an "anonymous" here document.

A variation of the above technique permits "commenting out" blocks of code.

Yet another twist of this nifty trick makes "self-documenting" scripts possible.

Here documents create temporary files, but these files are deleted after opening and are not accessible to any other process.

bash$ bash -c 'lsof -a -p $$ -d0' << EOF
> EOF
lsof    1213 bozo    0r   REG    3,5    0 30386 /tmp/t1213-0-sh (deleted)
	      

Some utilities will not work inside a here document.

For those tasks too complex for a "here document", consider using the expect scripting language, which is specifically tailored for feeding input into interactive programs.