Main index

Introducing UNIX and Linux


Getting started

Overview
Using UNIX
      Usernames
      Logging in
Logging out
Commands
      Typing in commands
      Commands and options
Communication with other users
      Email
      Other communication facilities
Files
      The editor Vi
            Vi commands (command mode)
            Vi commands (colon mode)
      Other editors
Input and output
      Scripts
      Here-documents
      Pipes
      Making copies of input and output
      Pagers
Emergencies
Getting help
Summary
Exercises

Here-documents

You will sometimes wish to give input to a command, where that input consists of a small number of lines - for example, if you want to create a script which, after it executes its commands, mails sam a message that is more than a single line.

One possibility would be to create a file for the message (mymessage, say), redirect the input for mailx to come from that file, and include the line

mailx sam <mymessage

as the last line of the script. This would work, but would involve creating two files (one for your script, and one for the message) rather than just one. In large scripts it might become confusing if too many files have to be created. Note that this would not be a problem if mailx was not in a script, as you could take the input to mailx from your terminal - but since the input to a script may be redirected from elsewhere this is not always possible.

A solution is known as a here-document. Following the symbol << comes a word, and all subsequent lines of standard input are treated as the standard input for the command, up to (but not including) that word. For instance,

mailx sam <<END
line 1 of message
...
last line of message
END

The line that terminates the input need not be END - any word will do. Try mailing yourself a message using a here-document. Although here-documents work perfectly well interactively, their principal use is in scripts.


Copyright © 2002 Mike Joy, Stephen Jarvis and Michael Luck