Here documents

From Linux Shell Scripting Tutorial - A Beginner's handbook
Jump to: navigation, search
← /dev/null discards unwanted outputHomehere strings →

To create a here document use the following syntax:

command <<HERE

This type of redirection tells the shell to read input from the current source (HERE) until a line containg only word (HERE) is seen. HERE word is not subjected to variable name, parameter expansion, arithmetic expansion, pathname expansion, or command substitution. All of the lines read up to that point are then used as the standard input for a command. Files are processed in this manner are commonly called here documents.


Use here document feature to give constant text to a command. For example the following command will count the words for input:

echo 'This is a test.' | wc -w

Sample outputs:


But, how do you count lots of lines at a time? Use here document as follows:

 wc -w <<EOF
> This is a test.
> Apple juice.
> 100% fruit juice and no added sugar, colour or preservative.

Sample outputs:


The <<, reads the shell input typed after the wc command at the PS2 prompts, >) up to a line which is identical to word EOF.

HERE document and mail command

For example, write an email using the mail command. Create a shell script called

# run tar command and dump data to tape
tar -cvf /dev/st0 /www /home 2>/dev/null

# Okay find out if tar was a success or a failure 
[ $? -eq 0 ] && status="Success!" || status="Failed!!!"

# write an email to admin 
mail -s 'Backup status'<<END_OF_EMAIL

The backup job finished.

End date: $(date)
Hostname : $(hostname)
Status : $status


Save and close the file. Run it as follows:

chmod +x

Sample outputs:

Subject: Test
From: root <>
Date: 12:57 Am

The backup job finished.

End date: Thu Sep 17 14:27:35 CDT 2009
Hostname :
Status : Success

The script provides the constant multi-line text input to the mail command.

← /dev/null discards unwanted outputHomehere strings →