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 Comments

mike  on May 28th, 2009

Nice trick dude!

rno  on June 3rd, 2009

Great!!!!!! I was looking for this one for a while.

Thx

Mariano  on March 11th, 2011

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

Mariano  on March 11th, 2011

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

Mariano  on March 11th, 2011

sorry for the spam

I found the solution

http://tldp.org/LDP/abs/html/here-docs.html

I used spaces instead of tab

;-)

Leave a Comment