A lesser-known feature of shell scripting is “here
documents” or heredoc. Basically, heredoc is a mechanism for working with large blocks of
text. From a readability standpoint, heredoc is
extremely useful. The code is easy to read, easy to work with, and very
Heredoc is especially handy when
you want to use a single statement to print many lines of text. For example,
assume you have written a script to automatically generate an e-mail message.
You might first write the text of the message to a temporary file, and then use
the system MTA to send it:
echo “From: $from” >>$tmpfile
echo “To: $to” >>$tmpfile
echo “” >>$tmpfile
echo “This is the first line of text.” >>$tmpfile
echo “This is the second line of text.” >>$tmpfile
This is cumbersome and difficult to read, and it’s certainly
more difficult than it should be to manipulate. Contrast that with the
following heredoc style:
cat <<EOT >$tmpfile
This is the first line of text.
This is the second line of text.
In this snippet, the cat
command is used to print out a block of text. The <<EOT string indicates that everything following is to be treated
as input until the string EOT is
reached. You can use any string that you like, but the terminating string must
be at the beginning of the line, so don’t indent it with any tabs or white
spaces. You can also make use of any variables previously defined; in this case,
the $from and $to variables would have been set in the script before they were
used in the heredoc statement.
To print this block of text to the terminal, omit the
redirector that was used (>$tmpfile), which redirected the output to the file
specified by the variable $tmpfile. If you omit that redirection, the text will
print to the screen.
Stay on top of the latest tech news with our free IT News Digest newsletter, delivered each weekday.
Automatically sign up today!