Wednesday, June 24, 2009

UNIX flavours and double evaluation

When I write shell scripts (ksh) I do not like to rely on a PATH so I tend to hardcode all UNIX executables. This means that they can generally run as is using cron.

Example


CAT=/usr/bin/cat
$CAT milk



However this is not very useful when mixing UNIX variants so I have come up with this way of coding so that we can catch as many UNIX flavours as possible

# Commands
typeset -u Command
for Name in cat date grep hostname mailx mv perl ps rm
do
Command=$Name

case $Name in
grep) PathNames=/usr/xpg4/bin:/usr/bin:/bin ;;
*) PathNames=/usr/bin:/bin ;;
esac

while [[ -n $PathNames ]]
do
PathName=${PathNames%%:*}
PathNames=${PathNames#*:}

if [[ $PathName = $PathNames ]]
then
PathNames=""
fi

if [[ -x $PathName/$Name ]]
then
eval "$Command=$PathName/$Name"
break
fi
done

if [[ -z $(eval print `print \\$${Command}`) ]]
then
print -u2 "Unable to find a $Name executable"
exit 1
fi
done
The bit I like the best is that last if statement which checks that the executable was found.


The eval command tries to print out, say, $CAT to check that the CAT variable has something in it, but as CAT is the value of the variable Command we have to do some jiggery pokery to get it to parse properly.

No comments:

Post a Comment