home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Unix Power ToolsUnix Power ToolsSearch this book

27.16. Here Documents

So far, we've talked about three different kinds of quoting: backslashes (\), single quotes ('), and double quotes ("). The shells support yet one more kind of quoting, called here documents. A here document is useful when you need to read something from standard input, but you don't want to create a file to provide that input; you want to put that input right into your shell script (or type it directly on the command line). To do so, use the << operator, followed by a special word:

sort >file <<EndOfSort
zygote
abacus
EndOfSort

This is very useful because variables (Section 35.9, Section 35.3) are evaluated during this operation. Here is a way to transfer a file using anonymous ftp (Section 1.21)[84] from a shell script:

[84]You might be better off using wget or curl for downloads, but this method can be useful for automated uploads.

Figure Go to http://examples.oreilly.com/upt3 for more information on: ftpfile

#!/bin/sh
# Usage:
#     ftpfile machine file
# set -x
SOURCE=$1
FILE=$2
GETHOST="uname -n"
BFILE=`basename $FILE`
ftp -n $SOURCE <<EndFTP
ascii
user anonymous $USER@`$GETHOST`
get $FILE /tmp/$BFILE
EndFTP

As you can see, variable and command substitutions (Section 28.14) are done. If you don't want those to be done, put a backslash in front of the name of the word:

cat >file <<\FunkyStriNG

Notice the funky string. This is done because it is very unlikely that I will want to put that particular combination of characters in any file. You should be warned that the C shell expects the matching word (at the end of the list) to be escaped the same way, i.e., \FunkyStriNG, while the Bourne shell does not. See Section 36.19.

Most Bourne shells also have the <<- operator. The dash (-) at the end tells the shell to strip any TAB characters from the beginning of each line. Use this in shell scripts to indent a section of text without passing those TABs to the command's standard input.

Other shells, notably zsh and later versions of ksh, but in the future possibly also bash, support a method for taking input from a string:

$ tr ... <<< "$xyzzy" | ...

-- BB



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.