Section 5.17. Here Documents


[Page 187 (continued)]

5.17. Here Documents

Earlier in the chapter, I briefly mentioned the << metacharacter. I delayed its full description until now, as really it's only used in conjunction with scripts and variables. When the shell encounters a sequence of the form:

$ command << word 


it copies its own standard input up to but not including the line starting with word into a shell buffer, and then executes command using the contents of the buffer as its standard input. Obviously, you should choose a sensible value for word that is unusual enough not to occur naturally in the text that follows. If no line containing just word is encountered, Bash and the Korn shell stop copying input when they reach the end of the script, whereas the C shell issues an error message. All references to shell variables in the copied text are replaced by their values. The most common use of the << metacharacter is to allow scripts to supply the standard input of other commands as inline text, rather than having to use auxiliary files. Scripts that use << are sometimes called here documents. Here's an example of a here document:


[Page 188]

$ cat here.sh         ...look at an example of a "here" doc. mail $1 << ENDOFTEXT Dear $1,  Please see me regarding some exciting news! - $USER ENDOFTEXT echo mail sent to $1 $ ./here.sh glass       ...send mail to myself using the script. mail sent to glass $ mail                ...look at my mail. Mail version 8.1 6/6/93.  Type ? for help. >N  1 glass@utdallas.edu Mon Feb  2 13:34   12/384 & 1                   ...read message #1. From: Graham Glass <glass@utdallas.edu> To: glass@utdallas.edu Dear glass,  Please see me regarding some exciting news! - glass & q                   ...quit out of mail. $ _ 





Linux for Programmers and Users
Linux for Programmers and Users
ISBN: 0131857487
EAN: 2147483647
Year: 2007
Pages: 339

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net