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

randolph.little rsl at cbnewsm.att.com
Tue Sep 11 04:52:45 AEST 1990


In article <563 at DIALix.UUCP>, bernie at DIALix.oz.au (Bernd Felsche) writes:
> 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?
> 
> 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
#                    ^^^   Should be $0
> 		break
> 		;;
# Add test for explicit current directory search:
	./*)	echo `pwd`/`basename $0`
		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.

The first change corrects a typo, where $i should be $0; while the
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>



More information about the Comp.unix.questions mailing list