Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!mnetor!seismo!ll-xn!nike!oliveb!glacier!mips!dce From: dce@mips.UUCP (David Elliott) Newsgroups: net.unix Subject: Bourne shell - $* and quoting Message-ID: <632@mips.UUCP> Date: Tue, 19-Aug-86 11:04:06 EDT Article-I.D.: mips.632 Posted: Tue Aug 19 11:04:06 1986 Date-Received: Wed, 20-Aug-86 23:09:48 EDT Reply-To: dce@mips.UUCP (David Elliott) Organization: MIPS Computer Systems, Sunnyvale, CA Lines: 62 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.