Using Here Docs («) in Linux


Here Document

Using a here document in Linux is often used for interactive purposes, for example, the ftp, or cat command. It should look something like this:

COMMAND <<EndLine
command #1
command #2
$varName
EndLine

All commands within the EndLine will be executed and read as input to the specified command. A real example could look like this:

sudo ftp -n $HOST <<SCRIPT
user $USER $PASSWD
get script.sh
get world.zip
get server.properties
quit
SCRIPT

All code above will be exected as input to the ftp command.

Wc example

The wc command is used to print different counts for a file. For example, wc -w will count all the words. It is used like this.

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

If we would like to count several lines, we can use here docs.

wc -w <<EOF
This is a test
This is a new line
hello
EOF

This will print the count of all words within the EOF.