protecting whitespace from the Bourne "for" command

Maarten Litmaath maart at cs.vu.nl
Tue Dec 11 04:03:27 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.  [...]

Another option is to use the ``set'' command, if the original $* arguments
aren't needed:

	# First remember the original args.

	argc=0
	argv=

	for i
	do
		argc=`expr $argc + 1`
		eval argv$argc='"$i"'
		argv="$argv \"\$argv$argc\""
	done

	# Now set the stuff we want to process.
	# The initial `x' is there to make sure the first argument of the
	# ``set'' command does not start with a `-'.  This method is more
	# portable than ``set - ...''.

	eval set x "$list"
	# Now get rid of the dummy arg.
	shift

	for item
	do
		# The `-e' option `protects' the pattern.
		grep -e "$item" $inputfile
	done

	# Reset the args.
	eval set x $argv
	shift

If the loop can be executed in a subshell, we don't need to remember the
args:
	(
		eval set x "$list"
		shift

		for item
		do
			...
		done
	)
--
In the Bourne shell syntax tabs and spaces are equivalent almost everywhere.
The exception: _indented_ here documents.  :-(
Does anyone remember the famous mistake Makefile-novices often make?



More information about the Comp.unix.shell mailing list