# argv.awk - print command-line parameters
BEGIN { for (x = 0; x < ARGC; ++x)
print ARGV[x]
print ARGC
}
This example also prints out the value of ARGC, the
number of command-line arguments. Here's an example of how it works
on a sample command line:
$ awk -f argv.awk 1234 "John Wayne" Westerns n=44 -
awk
1234
John Wayne
Westerns
n=44
-
6
As you can see, there are six elements in the array. The first
element is the name of the command that invoked the script. The last
argument, in this case, is the filename, "-", for standard input.
Note the "-f argv.awk" does not appear in the parameter list.
Generally, the value of ARGC will be at least 2.
If you don't want to refer to the program name or the filename, you
can initialize the counter to 1 and then test against ARGC -
1 to avoid referencing the last parameter (assuming that
there is only one filename).
Remember that if you invoke awk from a shell script, the command-line
parameters are passed to the shell script and not to awk. You have to
pass the shell script's command-line parameters to the awk program
inside the shell script. For instance, you can pass all command-line
parameters from the shell script to awk, using "$*". Look at the
following shell script:
awk '
# argv.sh - print command-line parameters
BEGIN {
for (x = 0; x < ARGC; ++x)
print ARGV[x]
print ARGC
}' $*
This shell script works the same as the first example of invoking awk.
One practical use is to test the command-line parameters in the
BEGIN rule using a regular expression. The
following example tests that all the parameters, except the first,
are integers.
# number.awk - test command-line parameters
BEGIN {
for (x = 1; x < ARGC; ++x)
if ( ARGV[x] !~ /^[0-9]+$/ ) {
print ARGV[x], "is not an integer."
exit 1
}
}
If the parameters contain any character that is not a digit, the
program will print the message and quit.
After testing the value, you can, of course, assign it to a variable.
For instance, we could write a BEGIN procedure of a
script that checks the command-line parameters before prompting the
user. Let's look at the following shell script that uses the phone
and address database from the previous chapter:
awk '# phone - find phone number for person
# supply name of person on command line or at prompt.
BEGIN { FS = ","
# look for parameter
if ( ARGC > 2 ){
name = ARGV[1]
delete ARGV[1]
} else {
# loop until we get a name
while (! name) {
printf("Enter a name? ")
getline name < "-"
}
}
}
$1 ~ name {
print $1, $NF
}' $* phones.data
The first example supplies the name on the command line, the second
prompts the user, and the third takes two command-line parameters and
uses the second as a filename. (The script will not allow you to
supply a filename without supplying the person's name on the command
line. You could devise a test that would permit this syntax, though.)