Contents | < Browse | Browse >
Executable `awk' Programs
-------------------------
Once you have learned `awk', you may want to write self-contained
`awk' scripts, using the `#!' script mechanism. You can do this on
many Unix systems (1) (and someday on GNU).
For example, you could create a text file named `hello', containing
the following (where `BEGIN' is a feature we have not yet discussed):
#! /bin/awk -f
# a sample awk program
BEGIN { print "hello, world" }
After making this file executable (with the `chmod' command), you can
simply type:
hello
at the shell, and the system will arrange to run `awk' (2) as if you
had typed:
awk -f hello
Self-contained `awk' scripts are useful when you want to write a
program which users can invoke without knowing that the program is
written in `awk'.
If your system does not support the `#!' mechanism, you can get a
similar effect using a regular shell script. It would look something
like this:
: The colon makes sure this script is executed by the Bourne shell.
awk 'PROGRAM' "$@"
Using this technique, it is *vital* to enclose the PROGRAM in single
quotes to protect it from interpretation by the shell. If you omit the
quotes, only a shell wizard can predict the results.
The `"$@"' causes the shell to forward all the command line
arguments to the `awk' program, without interpretation. The first
line, which starts with a colon, is used so that this shell script will
work even if invoked by a user who uses the C shell.
---------- Footnotes ----------
(1) The `#!' mechanism works on Unix systems derived from Berkeley
Unix, System V Release 4, and some System V Release 3 systems.
(2) The line beginning with `#!' lists the full pathname of an
interpreter to be run, and an optional initial command line argument to
pass to that interpreter. The operating system then runs the
interpreter with the given argument and the full argument list of the
executed program. The first argument in the list is the full pathname
of the `awk' program. The rest of the argument list will either be
options to `awk', or data files, or both.