Path: utzoo!utgpu!news-server.csri.toronto.edu!bonnie.concordia.ca!thunder.mcrcim.mcgill.edu!snorkelwacker.mit.edu!usc!zaphod.mps.ohio-state.edu!swrinde!cs.utexas.edu!sun-barr!newstop!sun!amdahl!krs From: krs@uts.amdahl.com (Kris Stephens [Hail Eris!]) Newsgroups: comp.unix.shell Subject: Re: Shell METACHAR's in parameters Message-ID: <11k701EV0dwd00@amdahl.uts.amdahl.com> Date: 22 Jan 91 16:49:53 GMT References: <829@marvin.jpl.oz> Reply-To: krs@amdahl.uts.amdahl.com (Kris Stephens [Hail Eris!]) Organization: Amdahl Corporation, Sunnyvale CA Lines: 72 In article <829@marvin.jpl.oz> david@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@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. ]