[Chapter 8] 8.18 Here Documents
Author: Jerry Peek, Tim O'Reilly & Mike Loukides
Date: 1998-08-04T21:34:35Z

#

| Chapter 8 How the Shell Interprets What You Type |

## 8.18 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 (6.8, 6.1) are evaluated during this operation. Here is a way to transfer a file using anonymous ftp (52.7) from a shell script:

>     #!/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, variables and command substitutions (9.16) 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 article 45.26.

[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. -JP]

- BB

8.17 verbose and echo Variables Show Quoting |  | 8.19 "Special" Characters and Operators