To create a here document use the following syntax:
command <<HERE text1 text2 testN $varName 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
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. > EOF
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 tapebackup1.sh:
#!/bin/bash # 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' email@example.com<<END_OF_EMAIL The backup job finished. End date: $(date) Hostname : $(hostname) Status : $status END_OF_EMAIL
Save and close the file. Run it as follows:
chmod +x tapebackup1.sh ./tapebackup1.sh
Subject: Test From: root <firstname.lastname@example.org> Date: 12:57 Am To: email@example.com The backup job finished. End date: Thu Sep 17 14:27:35 CDT 2009 Hostname : txvip1.simplyguide.org Status : Success
The script provides the constant multi-line text input to the mail command.