HERE Documents – Keeping Your Data with Your Script

Keeping Your Data with Your Script Problem

You need input to your script, but don’t want a separate file.

Solution

Use a here-document, with the << characters, redirecting the text from the command line rather than from a file. When put into a shell script, the script file then contains the data along with the script.

Here’s an example of a shell script in a file we call ext:

     $ cat ext
     #
     # here is a "here" document
     #
     grep $1 <<EOF
     mike x.123
     joe  x.234
     sue  x.555
     pete x.818
     sara x.822
     bill x.919
     EOF
     $

It can be used as a shell script for simple phone number lookups:

     $ ext bill
     bill x.919
     $

or:

Discussion

The grep command looks for occurrences of the first argument in the files that are named, or if no files are named it looks to standard input.

A typical use of grep is something like this: $ grep somestring file.txt

or:

$ ext 555
sue  x.555
$
$ grep myvar *.c

In our ext script we’ve parameterized the grep by making the string that we’re search- ing for be the parameter of our shell script ($1). Whereas we often think of grep as searching for a fixed string through various different files, here we are going to vary what we search for, but search through the same data every time.

We could have put our phone numbers in a file, say phonenumbers.txt, and then used that filename on the line that invokes the grep command:

     grep $1 phonenumbers.txt

However, that requires two separate files (our script and our datafile) and raises the question of where to put them and how to keep them together.

So rather than supplying one or more filenames (to search through), we set up a here-document and tell the shell to redirect standard input to come from that (tem- porary) document.

The << syntax says that we want to create such a temporary input source, and the EOF is just an arbitrary string (you can choose what you like) to act as the terminator of the temporary input. It is not part of the input, but acts as the marker to show where it ends. The regular shell script (if any) resumes after the marker.

We also might add -i to the grep command to make our search is case-insensitive. Thus, using grep -i $1 <<EOF would allow us to search for “Bill” as well as “bill.”