Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!swrinde!zaphod.mps.ohio-state.edu!samsung!uunet!mcsun!unido!mikros!mwtech!martin From: martin@mwtech.UUCP (Martin Weitzel) Newsgroups: comp.unix.shell Subject: Re: protecting whitespace from the Bourne "for" command Message-ID: <996@mwtech.UUCP> Date: 11 Dec 90 12:39:31 GMT References: <16570@cgl.ucsf.EDU> <4198@exodus.Eng.Sun.COM> Reply-To: martin@mwtech.UUCP (Martin Weitzel) Organization: MIKROS Systemware, Darmstadt/W-Germany Lines: 59 In article <4198@exodus.Eng.Sun.COM> mcgrew@ichthous.Eng.Sun.COM (Darin McGrew) writes: >In article <16570@cgl.ucsf.EDU> rodgers@maxwell.mmwb.ucsf.edu (ROOT) writes: >>Does anyone know how to protect whitespace in items to be passed to the >>"for" operator of the Bourne shell? Consider the script: > >Use `eval` so that the quotes are evaluated as such. Here's the >revised script-- > > #! /bin/sh > # > # Define list > # > list="'a b' c" > # > # Use list > # > eval for item in "$list" \; \ > do \ > grep \"\$item\" inputfile \; \ > done > # > # Script complete > >Yes, getting the quoting right can be difficult if the body of >the loop is large. Yes, getting the quoting right can be difficult :-( .... but I have found a simple trick that makes it much easier :-). Quoting is necessary as the shell essentially parses the arguments of the `eval'-command two times and the programmer must take care that some parts are evaluated in the first parse, others in the second. Most people now quote (only) the parts that must *not* be evaluated in the first parse. Make it vice versa and quote everything *except* what must be evaluated in the first parse. eval ' for item in '"$list"'; do grep "$item" inputfile; done ' Looks a little nicer, doesn't it? If you have hardcopy of this, there is another trick to see what's going on: Take one of this yellow marker pencils to highlite everything from one single qoute to the next. Leave out the unquoted parts. I'll try to show it here with capitals: eval ' FOR ITEM IN '"$list"'; DO GREP "$ITEM" INPUTFILE; DONE ' Everything that is highlited on your hardcopy (or capitalized above) is taken literally during the first parse. Easy to recognize that only the contents of the variable `list' will be substituted during this. -- Martin Weitzel, email: martin@mwtech.UUCP, voice: 49-(0)6151-6 56 83