« Mistletoe | Main | His Side of the Story »

February 27, 2006

Here Scripts

Q: I was reading some documentation which kept talking about a "here doc" - what is it and how can you use it?

A: Lots and lots of Unix commands have the ability to take input from their standard input. What you can do in a shell script (or a perl program) is to make use of this "standard input" feature by using a "
here doc".

This is done by redirecting the standard input of the command you are calling and the trick is knowing how to stop and revert to "normal" behaviour.

Here is an example:

# shell script stuff
someunixcommand <<!!
this input
is given
to someunixcommand
!!
# shell script continues from here...

In this case the "here doc" ends with !! but you can in fact use any characters instead as long as they will not occur inside the text of the "here doc". Also note that the ending character(s) must appear at the start of a line by themselves (so don't allow your editor to auto-indent that line).

The alternative would have been to put those lines in an external file and call it like this:

# shell script stuff
someunixcommand < externalfile
# shell script continues from here...

The downside is that you now have an extra file to manage and it may become separated or out of sync with the main program.

So next time you need to feed something to an external program, try a heredoc instead :-)

Posted by Ozguru at February 27, 2006 06:00 AM