Problem with sh/ksh quoting

Brad Appleton brad at SSD.CSD.HARRIS.COM
Thu Nov 1 07:51:38 AEST 1990


In article <16289 at s.ms.uky.edu> kherron at ms.uky.edu (Kenneth Herron) writes:
>I'm having a problem with quoting in shell scripts, exemplified by
>the following:
>
>line="this is 'a test'"
>
>for word in $line
>do
>	echo $word
>done
>
>I *want* it to produce:
>this
>is
>a test

For ksh, you can use an array:

	$ set -A  line  this is 'a test'
	$ for word in "${line[@]}"
	$ do
	$   echo $word
	$ done
	this
	is
	a test

Watch out though, in early version of ksh (earlier than ksh 11/16/88a)
using set -A will ALSO clobber your positional parameters ($1, $2, $*, $@)
and set them to the contents of your array in addition to setting your array.
If you have such a version of ksh you MAY have to do:

	$ set -A argv "$@"                         ## save $@
	$ set -A  line  this is 'a test'           ## set my array
	$ set --  "$@"                             ## restore $@

For sh, there are all sorts of tricks you can use but they are just that,
tricks. In the Bourne shell only "$@" preserves whitespace/IFS characters
in its arguments (whereas "${array[@]}" preserves whitespace/IFS characters
in ksh arrays).

A common Bourne shell trick is:

	$ line1=this
	$ line2=is
	$ line3='a test'

	$ i=0
	$ while [ $i -lt 3 ] ; do
	$   i=`expr $i + 1`
	$   eval echo \$line$i
	$ done
	this
	is
	a test

There are other "obscure" Bourne shell trick as well!
Hope this helps!
______________________ "And miles to go before I sleep." ______________________
 Brad Appleton           brad at ssd.csd.harris.com       Harris Computer Systems
                             uunet!hcx1!brad           Fort Lauderdale, FL USA
~~~~~~~~~~~~~~~~~~~~ Disclaimer: I said it, not my company! ~~~~~~~~~~~~~~~~~~~



More information about the Comp.unix.shell mailing list