protecting whitespace from the Bourne "for" command

Martin Weitzel martin at mwtech.UUCP
Tue Dec 11 23:39:31 AEST 1990


In article <4198 at exodus.Eng.Sun.COM> mcgrew at ichthous.Eng.Sun.COM (Darin McGrew) writes:
>In article <16570 at cgl.ucsf.EDU> rodgers at 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 at mwtech.UUCP, voice: 49-(0)6151-6 56 83



More information about the Comp.unix.shell mailing list