All You Wanted To Know About HERE Documents in Linux

By | 10/06/2013

5. Pipe the output of HERE documents as inputs to other commands

Yes, you can easily pipe the output of HERE documents to other commands.

Here is an example :

$ cat << EOF | wc -l
> Hi
> HOw are you
> EOF
2

So we see that the output of HERE document was was easily piped to wc command as input.

6. Using HERE documents with bash functions

HERE documents can easily be used with functions in bash scripts.

Here is an example :

#!/bin/bash
getEmployeeData ()
{
   read name
   read age
   read website
}

getEmployeeData << EOF
Allan
28
MyLinuxBook
EOF

echo $name
echo $age
echo $website

exit 0

Here is the output of the shell script shown above :

$ ./HEREfunc.sh 
Allan
28
MyLinuxBook

So we see that HERE documents can be easily used with script functions.

7. Use HERE documents for commenting code

Sometimes commenting out a large portion of code can be time-consuming. HERE documents can be used to easily comment out large block of code.

Here is an example :

#!/bin/bash

echo "Code comment start"

:<<COMMENT

getEmployeeData ()
{
   read name
   read age
   read website
}

getEmployeeData << EOF
Allan
28
MyLinuxBook
EOF

echo $name
echo $age
echo $website
COMMENT

echo "Code comment end"

exit 0

You can see that in script above, I have used the delimiter COMMENT (highlighted in bold) to comment out a large portion of code block.

Here is the output of this script :

$ ./HEREcomment.sh 
Code comment start
Code comment end

So we see that HERE documents can be used to easily comment out large portion of code blocks.

NOTE – These are also known as anonymous HERE documents.

8. Write HERE document to a file

This can be done in the following way :

$ cat << EOF > empStats
> Name
> Age
> Qualification
> Years of Experience
> Current company
> EOF
$ cat empStats 
Name
Age
Qualification
Years of Experience
Current company

So we see that the the file ‘empStats’ contained the desired text.

 

Here are some good resources containing/explaining practical usage of HERE documents:

 

One thought on “All You Wanted To Know About HERE Documents in Linux

Leave a Reply

Your email address will not be published. Required fields are marked *