|
Page 1 of 6 Here Documents A here document is a special-purpose code block. It uses a form of I/O redirection to feed a command list to an interactive program or a command, such as ftp, cat, or the ex text editor.
COMMAND <<InputComesFromHERE ... InputComesFromHERE
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 stdin of the program or command. It is similar to interactive-program < command-file, where command-file contains 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, such as, for example, wall. Example 18-1. broadcast: Sends message to everyone logged in #!/bin/bash
wall <<zzz23EndOfMessagezzz23 E-mail your noontime orders for pizza to the system administrator. (Add an extra dollar for anchovy or mushroom topping.) # Additional message text goes here. # Note: 'wall' prints comment lines. zzz23EndOfMessagezzz23
# Could have been done more efficiently by # wall <message-file # However, embedding the message template in a script #+ is a quick-and-dirty one-off solution.
exit 0 |
Even such unlikely candidates as the vi text editor lend themselves to here documents. Example 18-2. dummyfile: Creates a 2-line dummy file #!/bin/bash
# Non-interactive use of 'vi' to edit a file. # Emulates 'sed'.
E_BADARGS=65
if [ -z "$1" ] then echo "Usage: `basename $0` filename" exit $E_BADARGS fi
TARGETFILE=$1
# Insert 2 lines in file, then save. #--------Begin here document-----------# vi $TARGETFILE <<x23LimitStringx23 i This is line 1 of the example file. This is line 2 of the example file. ^[ ZZ x23LimitStringx23 #----------End here document-----------#
# Note that ^[ above is a literal escape #+ typed by Control-V <Esc>.
# Bram Moolenaar points out that this may not work with 'vim', #+ because of possible problems with terminal interaction.
exit 0 |
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. #!/bin/bash # Replace all instances of "Smith" with "Jones" #+ in files with a ".txt" filename suffix.
ORIGINAL=Smith REPLACEMENT=Jones
for word in $(fgrep -l $ORIGINAL *.txt) do # ------------------------------------- ex $word <<EOF :%s/$ORIGINAL/$REPLACEMENT/g :wq EOF # :%s is the "ex" substitution command. # :wq is write-and-quit. # ------------------------------------- done |
Analogous to "ex scripts" are cat scripts.
|