Here doc in bash

Introduction

A here document is a special-purpose code block or a kind of IO redirection which allows you to pass multiple lines of input to a command

Syntax

[COMMAND] <<[-] 'DELIMITER'
  HERE-DOCUMENT
DELIMITER
  1. COMMAND is any command you want to run
  2. « redirection, - is optional, when added, it will ignore leading tabs when passing content to command
  3. DELIMITER can be any string, usually EOF is used
  4. HERE-DOCUMENT here you can write content for here-doc e.g. commands, strings, variables
  5. DELIMITER same delimiter to end the here doc this should be at the start of line (white space is not allowed before ending delimiter)

Example

#!/bin/bash
cat << EOF
    current user is $USER
EOF

The above example can be interpreted as: take every line between EOF delimiters (resolve variables if any) and pass it to cat utility which will print it to console.

Assuming $USER is multix, the above script will output the following text (note that white space is preserved in the begining of the line)

    current user is multix

Single or double-quoted delimiter

If delimiter is enclosed in a single or double quote e.g. “EOF”, then variables in here-doc will not be resolved. See the follwoing example where EOF is surrounded by double quotes

#!/bin/bash
cat << "EOF"
    current user is $USER
EOF

this will generate the following output

    current user is $USER

I/O redirection and piping

Redirection and pipe operators can be used after the first delimiter.

#!/bin/bash
cat << EOF > out.txt
    current user is $USER
    another line
EOF

In above example, here doc will send current user is $USER and another line to cat utility which will send it to standard output, from there, > out.txt this output redirection will redirect the text to out.txt file.

Similarly, we can pipe the output to another program

#!/bin/bash
cat << EOF | grep "another"
    current user is $USER
    another line
EOF

In this example, output is passed to grep which will filter the line with another word and print it, the final output will be

    another line

top