[comp.unix.questions] funny in 'test'

davidsen@steinmetz.ge.com (William E. Davidsen Jr) (05/11/88)

  I had a user find a good (?) one the other day. She has a shell script
which did something like:
	if [ "$1" = "x" ]; then do something; fi

  The value passed in as the first argument was "-d". Now, the construct
"-d =" should test for a directory named "=", followed by a barf on the
operator "x". This script in fact compared strings on a number of
systems, and blew up on only a few. I believe that it should fail, but
would like some opinions on this.

  I fixed it by inverting the test, but it really looks as though some
shells assume a precedence of operators in the shell. A good reason
never to put ANY shell variable in the first position of an = test.
-- 
	bill davidsen		(wedu@ge-crd.arpa)
  {uunet | philabs | seismo}!steinmetz!crdos1!davidsen
"Stupidity, like virtue, is its own reward" -me

barmar@think.COM (Barry Margolin) (05/11/88)

In article <10778@steinmetz.ge.com> davidsen@steinmetz.ge.com (William E. Davidsen Jr) writes:
>	if [ "$1" = "x" ]; then do something; fi
>A good reason
>never to put ANY shell variable in the first position of an = test.

Another common convention is to put an extra character onto the front
of both parts of the test, e.g.

	if [ "x$1" = "xx" ]; ...

That way, if $1 starts with a hyphen, this becomes something like

	if [ "x-d" = "xx" ]

Barry Margolin
Thinking Machines Corp.

barmar@think.com
uunet!think!barmar

lew@gsg.UUCP (Paul Lew) (05/12/88)

 >   I had a user find a good (?) one the other day. She has a shell script
 > which did something like:
 > 	if [ "$1" = "x" ]; then do something; fi
 > 
 >   The value passed in as the first argument was "-d". Now, the construct
 > "-d =" ...

on BSD 4.* system, you will find out '[' is actually a link to
'/bin/test' and it is NOT part of the shell.  Test expect a lot of
flags; -r, -w, -f, -d, -s, -t -z -n, etc (see man page for test).  If
you need string comparison, always prefix by other characters like:

	if [ "_$1" = "_$x" ]; then ...

(system V sh has test built-in, probably interprete '[' to be 'test' like
BSD?)
-- 
Paul Lew			{oliveb,harvard,decvax}!gsg!lew	(UUCP)
General Systems Group, 5 Manor Parkway, Salem, NH 03079	(603) 893-1000