Shell/gawk interaction

Chuck Karish karish at mindcraft.com
Fri Dec 14 16:32:28 AEST 1990


In article <247 at locke.water.ca.gov> rfinch at caldwr.water.ca.gov
(Ralph Finch) writes:
>I do not understand why the following bourne shell script generates an
>error in the awk program:
>
>filename=$1 ; shift
>nargs=$#  
>args="$*"
>echo $args
>
>gawk '
>BEGIN {
>args="'$args'"
>print args
>exit 
>}' $filename

The shell argument on line 3 of the awk program ($args) is outside
the single quotes (as it must be, to be interpreted by the shell
rather than by awk).  It must be interpreted as a single token
by the shell if the program is to be passed to awk properly.
What happens is that the shell sees the spaces between the
args in $args and sends $# - 1 arguments to awk when it should
always send two, the program and the filename.  If you want to
check this out, replace 'gawk' in the script with the name of
a script that reads:

#! /bin/sh
echo $#

Fix the problem by adding double quotes:

args="'"$args"'"

The inner double quotes are interpreted by the shell to group $args
into a single variable.  The single quotes protect the rest of the awk
program from interpretation by the shell.  The outer double quotes
tell awk that the string produced by the shell on interpreting $args is
a literal to be assigned to the awk 'args' variable, rather than a
variable name.

Another way to solve the problem is to change $IFS between the time
you set "$args" and the time you interpret it.

Thanks for asking the question.  I've known for a long time that spaces
in this context cause problems, but had never taken the time to figure
out why.
-- 

	Chuck Karish		karish at mindcraft.com
	Mindcraft, Inc.		(415) 323-9000		



More information about the Comp.unix.shell mailing list