Wed, 25 Jan 2006

Bad Shell Scripts

I'm always amazed at the number of bad shell scripts I keep coming across. Take this snippet for example:

TEMP1=`mktemp /tmp/tempenv.XXXXXX` || exit 1
perl $CONF_DIR/project.pl $@ > $TEMP1
if [ $? != 0 ]; then
  return
fi

. $TEMP1
rm -f $TEMP1

There are several things wrong with this. First it uses a temporay file. Secondly it uses more processes than are required and thirdly it doesn't clean up after itself properly. If perl failed, the temp file would still be created, but not deleted. The last problem can be solved with some suitable uses of trap:

TEMP1=`mktemp /tmp/tempenv.XXXXXX` || exit 1
trap "rm -f $TEMP" INT TERM EXIT
perl $CONF_DIR/project.pl $@ > $TEMP1
if [ $? != 0 ]; then
  return
fi

. $TEMP1
rm -f $TEMP1
trap - INT TERM EXIT

Of course this can all be replaced with a single line:

eval $(perl $CONF_DIR/project.pl $@)
[, , ] | # Read Comments (1) |

Related Products

Comments

Have a look at the Useless Use of Cat Award

http://www.ruhr.de/home/smallo/award.html
Posted by Ken Bloom at Fri Jan 27 02:39:58 2006

Name:


E-mail:


URL:


Comment:


Please enter "fudge" to prove you are a human