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:
$ ext 555 sue x.555 $
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:
$ grep myvar *.c
In our ext script we’ve parameterized the
grep by making the string that we’re searching 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 ...
Get bash Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.