Which script (was Re: comp.unix.questions)
Bernd Felsche
bernie at DIALix.UUCP
Sat Sep 15 20:06:50 AEST 1990
In article <1990Sep10.185245.25531 at cbnewsm.att.com> rsl at cbnewsm.att.com (randolph.little) writes:
>In article <563 at DIALix.UUCP>, bernie at DIALix.oz.au (Bernd Felsche) writes:
>> The solution is to parse the current PATH if the program name does
>> not begin with a '/'. On a BSD machine, you can use the 'which'
>> command (come Sys V have it also), or you can work it out by:
>>
[some script deleted]
>> prog=$0
>> case $prog in
>> /*) echo $i
># ^^^ Should be $0
>> break
>> ;;
># Add test for explicit current directory search:
> ./*) echo `pwd`/`basename $0`
^^^^^^^^^^^^^^^^^
This will break if somebody uses ./bin/whodo or something. Even
worse, you (and I) neglected to check for the existence and execute
permissions.
What about ../* ??
After posting, I did notice the deficiency, (actually woke up in the
middle of the night!) I trust that the end-use is not in a
life-threatening environment :-)
> break
I could use one...
[...rest of script deleted...]
>
>The first change corrects a typo, where $i should be $0; while the
Sprung! I actually kludged my "which" script to include in the
message.
>second change adds another pattern to handle the case where the command
>is invoked in the working directory by typing ./command (which bypasses $PATH).
>
>Randolph S. Little <randolph.little at att.com>
Thank you for your vigilance. Constructive criticism should be
rewarded.
So here's the which script, it can be easily tailored to suit the
original request... barring typos!
Some serious testing has gone into this, so please let me know if
I've missed something.
I don't want to put shell function (or korn shell aliases) into it.
If you're that way inclined, please post the results.
------------------------------- cut here -----------------------
:
# bourne shell which
#
# which what? :-)
#
# By Bernd Felsche. bernie at DIALix.oz.au
#
# bug with relative paths fixed Sat Sep 15 17:23:32 WST 1990
#
if [ $# = 0 ]
then
echo "usage: $0 program [program...]" 1>&2
exit 1
fi
for prog in $* ; do
path="NO PATH AVAIL"
case $prog in
/*) path=$i
;;
./*|../*)
dir=`dirname $prog`
if [ -d $dir ] ; then
path=`(eval cd $dir ; pwd)`/`basename $prog`
fi
;;
*) OIFS="$IFS"
IFS=":$IFS"
for i in $PATH ; do
if [ -f $i/$prog -a -x $i/$prog ] ; then
path=$i/$prog
break # for $PATH
fi
done
IFS="$OIFS"
;;
esac
if [ -x $path -a -f $path ] ; then
echo $path
else
echo $prog not found 1>&2
exit 2
fi
done
------------------------- end -----------------------
bernie
P.S. bug reports & critiques welcome.
More information about the Comp.unix.questions
mailing list