Bourne shell - $* and quoting

David Elliott dce at mips.UUCP
Wed Aug 20 01:04:06 AEST 1986


In a recent posting, the following shell function was given:

	not() {
		$*
		if [ $? -eq 0 ]
		then return 1
		else return 0
		fi
	}

I'd like to get picky for a moment here for the benefit of all shell
programmers, particularly the beginners, as it pays to have good
programming habits.

The above function will not work as expected in cases where the arguments
contain characters special to the shell. For example,

	not echo '*' 

will actually expand * instead of just printing an asterisk. There are
many examples that can do the same thing.

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).

As a side point, variables should always be quoted unless you know what is
in them. This means that any variable that could be set from data given
by a user should be placed in double quotes. It really scares me to see
something like:

	if [ x-q = x$1 ]
	...

since I could easily make $1 something like " -o 1 -eq 1". The really
funny part is that the author is very careful to put the x in front
of the arguments to avoid syntax errors. I think that the proper way
of giving arguments to 'test' is:

	[ " $string" = " value" ]

This looks good, is safe, and it works.

When I tell this to people, I sometimes get the excuse "I'm the only one
that will ever use it, and I would never do anything silly like having a
filename with a space or semicolon in it". Just remember that today's
beginners are tomorrow's wizards, and that little shell script you write
today may be something that you end up giving to tomorrow's beginners;
people that can stand in awe of your mistakes as well as your wizardry.

			David

A good evaluator is someone that can break something "without" looking at it.



More information about the Comp.unix mailing list