Unix question

ron

Member
Can someone tell me how to find out the full path name of the current script.

I tried $0 but it just gives you the command that invoked the script ... and if you invoke the script without specifying the full path then $0 only gives you the file name.

Any ideas?

Ron.

(PS: I'm using Solaris 8.)
 

drunkahol

New Member
We use

`dirname $0`

to get the directory of the script under Tru64. Which shell are you using, as this could differ between shells.

Our scripts run as /bin/ksh from cron entries.

Duncan
 

ron

Member
Thanks, Duncan.

I use ksh also ... and do the same as you (although I use the $(...) syntax).

It works ... but only in the rather strict environment of an execution triggered from cron where one must specify a full path for the script to be executed. Thus, if the entry in cron says something like:

2 6 * * * /u/bin/bla.ksh

... then script bla.ksh can use `dirname $0` and get "/u/bin" as the value ... which is what's wanted.

But if (say) script bla.ksh calls another script like this:

./blob.ksh

... then script blob.ksh cannot discover the name of itself ... unless there is an arrangement set-up between the scripts. No problem setting-up such arrangements ... but I was curious to know if there was a particular way for a script to find-out for sure exactly what the name is of itself (or, more particularly, the name of the directory that contains it).

Ron.
 

methyl

Member
Try the ksh builtin "whence". This tells you where the script would be found down the current path if you didn't type any of the full hierarchic name. This quick approach only works if you rely on $PATH to find the script. (To detect other common ways of calling the script you'd need to look at the first character of $0, taking special action for "." and "/").

whence <filename>
Null reply means that you won't find the program down the current PATH.

#!/bin/ksh
PN="`basename $0`" # Name of the script file
CAMEFROM=`whence "${PN}"` # First occurance of this script in current PATH
echo "${CAMEFROM}" # Full hierarchal name of the script OR blank if
# script is not in the PATH

By the way, "whence -v <filename>" can be most revealing if your script name is the same as a shell command. e.g. "whence -v test" .
 
Top