Determining absolute PATH within KSH script

Hey everyone,

I'd like to determine the absolute path of where a script resides from within the same script. For example, I have a script - /tmp/myscript. Regardless of how that script is call - '/tmp/myscript', 'cd /tmp;./myscript', '. /tmp/myscript' - I'd like to be able to determine - from within 'myscript' - that it's located in '/tmp'.

I've tried combinations of ${PWD}, ${0}, ~+, but nothing has worked, esp. when sourcing the script.

Any ideas will be GREAT appreciated (I've spent almost a day trying to figure this out).

Thanks.

If it has to work all the time, it's impossible. There is no hope with something like:
cat /tmp/myscript | ksh
There is also no hope when sourcing the file.

$0 should work in most other cases, in fact, I can't think of another case where it fails. If $0 is a relative path, you may want to tranform it into a absolute path.

It is low-tech, but you could put a line:
MYPATH=/tmp/myscript
in the script. If the script is running as root, the script can invoke fuser on MYPATH and verify that the current process at least has the file open.

That - it's impossible - is what I've been afraid of. And am surprised about - I really thought I'd find something. I have made something work up to this point using a combination of ${PWD} and ${0} but sourcing screwed that up.

I'm trying to stay away from hardcoding anything with regards to the parent path so that I can have "production" and "dev" copies of scripts with identical subdirectory structures.

Anyway, thanks for the reply.

The following works fine for me on hp/ux - ksh:

if [[ $0 != "/"* ]]; then
myPath=`pwd`
else
myPath=`dirname $0`
fi
echo $myPath

Maybe I missed something :wink:

Thanks for the reply. I do appreciate the input. One problem with the code though - trying sourcing the script and you'll get the directory you sourced the script from and not the directory the script is in. For example:

cd /home/myhome
. /tmp/myscript
myPath = /home/myhome

Oops you are right: when sourcing my script, the os sees only -ksh as $0 during execution, w/o any $1 etc.... :frowning: