[comp.unix.questions] Finding a script's location

karish@mindcrf.UUCP (Chuck Karish) (09/11/90)

[ This thread belongs in comp.unix.shells.  I've directed
followups there. --crk ]

In article <9434@uudell.dell.com> rjd@ninja.dell.com writes:
>In article <1990Sep7.152354.9439@ecn.purdue.edu>
patkar@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.
>
>   Hmmmmm..... Off the top of my head, how about this?:
>
>COMMAND=`basename $0`
>DIR=`type $COMMAND | sed -e 's:^.* /:/:' -e "s:/$COMMAND$::"`
>echo "Parent directory of \"$COMMAND\" is \"$DIR\""

Does this work if the script is somewhere in the search path, and
$0 is not a path?

When I have to do this, I consider three cases:

- $0 contains an absolute path.
- $0 contains a relative path.
- $0 contains a command name that's not a path.

If $0 starts with a / (absolute path name), just clip off the file name:
CMD=$0
DIR=`echo $CMD | sed 's:/[^/]*$::'`

If $0 contains a / but does not start with one (relative path name),
do CMD=`pwd`/$0 before using sed as above.

If $0 contains a command that your login shell found by searching
its $PATH or $path, repeat that logic (or use `which`, if all
your systems use it): see whether there's a file you can execute
in any of the directories in $PATH, by searching them in order
and using test -x.  Then clip off the file name with sed.

If the shell script has mucked with $0 (can shells do this?  C programs
sure can) you're hosed: in general, you can't get there from here.

Depending on your specific needs, you may or may not wish to
add code to eliminate './' and '../' from the paths.

If anyone knows a way to do this that's simpler and
still maximally portable (to UNIX systems) I'd like to
hear about it.  Ditto for anything I've left out.
-- 

	Chuck Karish		karish@mindcraft.com
	Mindcraft, Inc.		(415) 323-9000