Passing variables to gawk

Skip to first unread message

Larry Wall

Jan 18, 1990, 9:47:07 PM1/18/90
In article <> (Mike McManus) writes:
: I want to pass variables to a gawk program via the command line. According to
: the man page, all you need do is call gawk with <var>=<value> instead of file
: names:
: gawk -f foo.awk a=1 b=2 c=3 infile > outfile
: and the variables a,b,c will be free to use in foo.awk (the gawk script), and
: will be assigned the values 1,2,3. I can't seem to get this to work! When I
: print the value of the variables inside a BEGIN{} block in foo.awk, they are
: all set to 0. Anybody have any experience with this that they'd like to
: share?

I believe this is called "bug emulation". awk itself has the same problem.

(It is possible that this was not considered a bug when first implemented.
I can imagine someone wishing to override the BEGIN section from the command
line. Let us be charitable, and call it a misleading feature :-)

I chose not to emulate this particular misleading feature in the awk-to-perl
translator. The produced perl script evaluates the foo=bar switches before
doing the "BEGIN" stuff. If you want the other behavior, you can just move
the line that does that, which says

eval '$'.$1.'$2;' while $ARGV[0] =~ /^([A-Za-z_]+=)(.*)/ && shift;

down below the stuff derived from BEGIN.

Oddly enough, in the version of nawk I have access to, it is documented
to have the buggy behavior, but, in fact, works right. Go figure.

Larry Wall

Reply all
Reply to author
0 new messages