Indenting bourne shell here documents

The Bourne shell provides here documents to allow block of data to be passed to a process through STDIN. The typical format for a here document is something similar to this:

command <<ARBITRARY_TAG
data to pass 1
data to pass 2
ARBITRARY_TAG

This will send the data between the ARBITRARY_TAG statements to the standard input of the process. In order for this to work, you need to make sure that the data is not indented. If you indent it for readability, you will get a syntax error similar to the following:

./test: line 12: syntax error: unexpected end of file

To allow your here documents to be indented, you can append a “-” to the end of the redirection strings like so:

if [ "${STRING}" = "SOMETHING" ]
then
        somecommand <<-EOF
        this is a string1
        this is a string2
        this is a string3
        EOF
fi



You will need to use tabs to indent the data, but that is a small price to pay for added readability. Nice!

5 thoughts on “Indenting bourne shell here documents”

  1. hello could you help me?

    what am I missing?

    [mariano@casa scripts]$ bash provaindent.bash
    provaindent.bash: line 13: syntax error: unexpected end of file
    [mariano@casa scripts]$ cat provaindent.bash
    #!/bin/bash

    i=0
    rm -f ciao

    while [ $i -le 10 ]; do

    cat>> ciao <<- EOF
    $i
    EOF
    let i=i+1
    done

  2. Hi

    I can do this but I do not want my ciao file indented

    [mariano@casa scripts]$ cat provaindent.bash
    #!/bin/bash

    i=0
    rm -f ciao

    while [ $i -le 10 ]; do

    cat>> ciao <<- EOF
    $i
    EOF
    let i=i+1
    done
    [mariano@casa scripts]$ cat ciao
    0
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10

Leave a Reply

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