Open Source

Use 'heredoc' in shell scripts

Linux users who work with large blocks of text may want to consider using heredoc. Find out how to use heredoc in a single statement to print many lines of text in a shell script.

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 straightforward.

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
From: $from
To: $to

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!

About Vincent Danen

Vincent Danen works on the Red Hat Security Response Team and lives in Canada. He has been writing about and developing on Linux for over 10 years and is a veteran Mac user.

Editor's Picks