Which script (was Re: comp.unix.questions)

Bernd Felsche bernie at DIALix.oz.au
Sun Sep 9 22:32:42 AEST 1990


In article <1990Sep7.152354.9439 at ecn.purdue.edu> patkar at helium.ecn.purdue.edu (The Silent Dodo) writes:
>I have a question about shell scripts.  How can a shell script
>(sh or csh) find out its own file name?  Actually, I need to
>know only the directory in which it resides.
>
The trivial solution is that the program name is in $0.

Since you want the path (directory), it is only partially useful,
because the program name is what you actually typed.  So if you
typed 'freddo', then $0 becomes that... no path.

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:

:
# bourne shell script template
#

prog=$0
case $prog in
	/*)	echo $i
		break
		;;
	*)
		OIFS="$IFS"
		IFS=":$IFS"

		for i in $PATH
		do
			if [ -x $i/$prog ]
			then
				break
			fi
		done
		echo $i/$prog
		IFS="$OIFS"
		;;
esac

Instead of the echo's, you can use a fullname= etc to find what you
need.  To get the directory name is left as an exercise :-)

bernie

p.s.  Send no cash.  Just Bullion.



More information about the Comp.unix.questions mailing list