protecting whitespace from the Bourne "for" command

Darin McGrew mcgrew at ichthous.Eng.Sun.COM
Sat Dec 8 13:23:17 AEST 1990


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.  Another option might be to have a small loop
that feeds a `while read foo` loop--

	eval	for item in $list \; \
		do \
			echo \"\$item\" \; \
		done |
	while read item
	do
		grep "$item" inputfile
		# More big, hairy, loop that would be too
		# confusing with '\' characters everywhere
	done

Darin McGrew			mcgrew at Eng.Sun.COM
Affiliation stated for identification purposes only.



More information about the Comp.unix.shell mailing list