Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

262 Process Control Chapter 8


Example


Acommon use for the optional argument following the interpreterpathnameis to
specify the-foption for programs that support this option. For example, anawk( 1 )
program can be executed as
awk -f myfile
which tellsawkto read theawkprogram from the filemyfile.

Systems derived from UNIX System V often include two versions of theawklanguage. On
these systems,awkis often called ‘‘oldawk’’ and corresponds to the original version
distributed with Version 7. In contrast,nawk(newawk)contains numerous enhancements and
corresponds to the language described in Aho, Kernighan, and Weinberger[ 1988 ].This newer
version provides access to the command-line arguments, which we need for the example that
follows. Solaris 10 provides both versions.
Theawkprogram is one of the utilities included by POSIX in its 1003.2 standard, which is now
part of the base POSIX.1 specification in the Single UNIX Specification. This utility is also
based on the language described in Aho, Kernighan, and Weinberger[ 1988 ].
The version ofawkin Mac OS X 10.6.8 is based on the Bell Laboratories version, which has
been placed in the public domain. FreeBSD 8.0 and some Linux distributions ship with GNU
awk,calledgawk,which is linked to the nameawk.gawkconforms to the POSIX standard, but
also includes other extensions. Because they aremoreup-to-date,gawkand the version ofawk
from Bell Laboratories arepreferred to eithernawkor oldawk.(The Bell Labs version ofawk
is available athttp://cm.bell-labs.com/cm/cs/awkbook/index.html.)

Using the-foption with an interpreter file lets us write
#!/bin/awk -f
(awk program follows in the interpreter file)
For example, Figure8.21 shows/usr/local/bin/awkexample(an interpreter file).
#!/usr/bin/awk -f
#Note: on Solaris, use nawk instead
BEGIN {
for (i = 0; i < ARGC; i++)
printf "ARGV[%d] = %s\n", i, ARGV[i]
exit
}

Figure 8.21 Anawkprogram as an interpreter file

If one of the path prefixes is/usr/local/bin, we can execute the program in
Figure8.21 (assuming that we’ve turned on the execute bit for the file) as
$awkexample file1 FILENAME2 f3
ARGV[0] = awk
ARGV[1] = file1
ARGV[2] = FILENAME2
ARGV[3] = f3
Free download pdf