Shell METACHAR's in parameters

Kris Stephens [Hail Eris!] krs at uts.amdahl.com
Wed Jan 23 03:49:53 AEST 1991


In article <829 at marvin.jpl.oz> david at marvin.jpl.oz (David Magnay) writes:
>Can anyone supply a "rule" of how to consistently handle shell parameters inside
>a script, when the parameter MAY contain shell meta-characters or a regular
>expression. The danger is that the shell is will process the characters, rather
>than pass them literally.

I first tripped over this with a USAGE variable:

	USAGE="usage: $0 [-f] filename"
	if [ somebadcondition = true ]
	then
		echo $USAGE 1>&2
		exit 1
	fi

and what happened, based on PWD, was that I'd get 

	usage: thecmd f filename

"What happened to the brackets and the minus-sign???", I asked myself.
Well, of course, there was a file named "f" in PWD, and it was matched
by the   [-f]   term in the USAGE variable, and so replaced that term.
Here's one fix:

	USAGE="usage: $0 [-f] filename"
	if [ somebadcondition = true ]
	then
		echo "$USAGE" 1>&2
		exit 1
	fi

because, once quoted, only the first level of evaluation by the shell
remains (ie. the variable is replaced by its contents and the contents
aren't further evaluated).  *Every* time you reference a variable which
you either know to contain shell meta-characters or suspect might (as
the result of a read or user-arguments), double-quote it.

By the way, if you use ksh, you have an alternative (though the use of
double-quotes is identical).  If you    set -f    , then no shell
meta-characters are matched in filename generation.  This is switchable,
so you can

	while read re
	do
		if [ ! -z "$re" ]
		then
			set -f
			grep $re somefile
			set +f
		fi
	done

Note that even if you're running the whole script under 'set -f', you
still have to quote "$re" in the test to see if it's non-null, because
if it *is* null, test will report a missing argument.

When the user, on calling the script, entered

	thecommand -f file*

without quoting file* as either "file*" or 'file*' or file\*, the meta-
character matching was done before your script got control.  If there
were fourteen files in PWD starting with "file" in their names, then
thecommand was called with -f and fourteen filename arguments.  Such
is life when the user's command-environment is a programming language.

...Kris
-- 
Kristopher Stephens, | (408-746-6047) | krs at uts.amdahl.com | KC6DFS
Amdahl Corporation   |                |                    |
     [The opinions expressed above are mine, solely, and do not    ]
     [necessarily reflect the opinions or policies of Amdahl Corp. ]



More information about the Comp.unix.shell mailing list