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 (, ) are evaluated during this operation. Here is a way to transfer a file using anonymous ftp () 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 () 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 .
[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