Home > Programming, Technology, Uncategorized > Here documents in bash

Here documents in bash

In my day to day work oftentimes I work with C, Bash scripting and Cross compiling for ARM and other interesting stuff. I feel programming is an art so as bash scripting. There are many things we come across after seeing the scripts written by highly experienced bash programmers. One of such concept was a here document.

In simple terms,

here documents can be treated as multiple line input provided to a command in a shell script.

Let us discuss here documents with simple examples:

Example 1:

wc -l << COUNT_LINES
Vasanth Raja

In the above example the start and end of the here document are specified with “COUNT_LINES“. Input to “wc -l” command is the three lines in between the COUNT_LINES. As expected the output to this is “3“.

Example 2:

Oftentimes I see the here documents used in conjunction with cat. This is because when we want to print set of lines to the terminal, this comes in handy. For example


The invoked script name: $0
This invoked script direcotry: `dirname $0`
This is a second line


Few important points are

1. In here documents we can substitute command outputs.

In the above example $0 and `dirname $0` are replaced with the command outputs.

2. All the text in the here document will be printed exactly to the standard output. That means leading tabs, spaces are preserved exactly.

Suppose if you wish to remove the leading tabs from the here document, the same can be achieved in the following manner

cat << – USAGE_HELP

The invoked script name: $0
This invoked script direcotry: `dirname $0`
This is a second line


Just use a ‘-‘ symbol just after the symbol “<<“.

In a nutshell, here documents comes very hand when you want to give multiple line input to a command. Moreover, here documents are simple to use and easy to understand.

  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: