I managed to add two more sections to my article on writing
robust shell scripts
including using trap and making more atomic
changes. Had some useful feedback including making the fact that a few
small tweaks made it apply to more than just bash. Following from that
I’ve added an article about changing your bash
prompt
and how mine has
been built up over the years to something useful to me. Hopefully it’ll
give other people some ideas.

Yesterday I posted about some bad
shell
code I had found and posted an improved version. Part of the
reason for posting it was that I hoping someone could point out any
errors in the version I posted. Fortunately Neil Moore emailed me some
improvements.

  1. If the script returns more than one line they will be removed by the
    $(…) expansion when it is split into words. The solution there is to
    surround it in double quotes.
  2. The next problem Neil pointed out was that $@ should be
    surrounded by quotes in pretty much every case, otherwise parameters
    with spaces in will get split into separate parameters.
  3. The final problem is that if the script includes a return statement, it
    will stop the inner most function or sourced script, but not during
    eval.The solution is to enclose it in a function:

    
    dummy() { eval "$(perl "$CONF_DIR/project.pl" "$@")"; } dummy "$@"
    
    

Since making the post, I discovered that Solaris’ /bin/sh
doesn’t like $(...), so it’s probably better to use backticks
instead if you want to be portable. As I know the output from the script
I’m not worried about return statements, so I’ve ended up with:


eval "`perl "$CONF_DIR/project.pl" "$@"`"

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 $@)