Bourne shell - $* and quoting

Jerry Peek jerryp at tektools.UUCP
Fri Aug 29 02:35:40 AEST 1986


In article <632 at mips.UUCP> dce at mips.UUCP (David Elliott) writes:
> The basic rule here is: $* is like goto; use it only when you can't get
> the job done otherwise. The proper variable to use is "$@". For those of
> you unfamiliar with "$@", the explanation is:
> 
> 	$*	$1 $2 $3 ...
> 	"$*"	"$1 $2 $3 ..."
> 	"$@"	"$1" "$2" "$3" ...
> 
> In other words, "$@" prevents further processing of special characters, and
> is therefore safe (except for a "bug" that says that if $* is empty, "$@"
> will expand to "" instead of being empty).

I thought I'd add my two cents' worth -- on a related topic.

When they want to loop on all the commandline arguments, some people write
"for" loops this way, with $*:

	for var in $*
	do
	  blah blah
	  ...
	done

This gets you into the same problem that David mentioned... commandline
arguments will be re-scanned.  It's much better to use the default, which
*does* preserve the commandline arguments:

	for var
	do
	  ...

This is equivalent to:

	for var in "$@"
	do
	  ...

(except for the null-string bug that David mentioned).  BTW, lots of
Bourne shell manual pages say that 'for var' is equivalent to 'for var in $*',
but that's not true -- at least, not on any Bourne Shell I've seen.

--Jerry Peek, Tektronix, Inc.
US Mail:    MS 74-222, P.O. Box 500, Beaverton, OR 97077
uucp:       {allegra,decvax,hplabs,ihnp4,ucbvax}!tektronix!tektools!jerryp
CS,ARPAnet: jerryp%tektools at tektronix.csnet
Phone:      +1 503 627-1603



More information about the Comp.unix mailing list