[comp.unix.questions] sh feature: redirection of flow control bug

daveb@laidbak.UUCP (Dave Burton) (01/24/88)

This is an ancient (but still present) bug,
so apologies if I'm reviving a dead subject.

I just had occasion to use a feature of the Bourne/Korn shells,
I/O redirection of the flow control statements. The following
script demonstrates a bug present in sh and absent in ksh:

#!/bin/sh	# replace with $WHEREEVER/bin/ksh
if [ ! -d "$1" ]
then	echo "'$1' not a dir"
	exit 1
fi >&2
cd $1
echo "hello from `pwd`"
exit 0

This fails with sh and works with ksh.
Output from the sh version:

	Script started on Sat Jan 23 11:12:34 1988
	laidbak:1% x .
	hello from /u3/daveb
	laidbak:2% x x
	'x' not a dir
	x: x: bad directory
	laidbak:3% exit
	script done on Sat Jan 23 11:12:52 1988

Output from the ksh version:
	Script started on Sat Jan 23 11:14:23 1988
	laidbak:1% x .
	hello from /u3/daveb
	laidbak:2% x x
	'x' not a dir
	laidbak:3% exit
	script done on Sat Jan 23 11:14:58 1988

I haven't tested, but I'm sure {for,while}do/done and
case/esac exhibit the same behavior as the if/fi.

The workaround is easy (if inelegant): redirect output
of each individual command; or set a flag and test it
upon completion of the if/fi.

Is there a better/preferred workaround?
The encapsulated command list is small in this
example; adding more command to the list makes
individual redirection tiresome.

Hacking the shell is out - several of the systems
this code will execute on have no source available.
And please, no sh/csh/ksh flames/merit discussions.
-- 
--------------------"Well, it looked good when I wrote it"---------------------
 Verbal: Dave Burton                        Net: ...!ihnp4!laidbak!daveb
 V-MAIL: (312) 505-9100 x325            USSnail: 1901 N. Naper Blvd.
#include <disclaimer.h>                          Naperville, IL  60540

schaefer@ogcvax.UUCP (Barton E. Schaefer) (01/29/88)

A working version of the script in question:

#! /bin/sh
if [ ! -d "$1" ]
then    echo "'$1' not a dir"
        exit 1
else	exit 0
fi >&2 || exit 1
cd $1
echo "hello from `pwd`"
exit 0
-- 
Bart Schaefer			CSNET:	schaefer@cse.ogc.edu
				UUCP:	...{tektronix,verdix}!ogcvax!schaefer
"You can lead a yak to water, but you can't teach an old dog to make a silk
purse out of a pig in a poke."			-- Opus