access the script path/name in a sourced script

access the script path/name in a sourced script

Post by Andrei Kazaro » Sat, 23 Mar 2002 02:04:09


How to calculate a full path to the script in a script which is being
sourced ?

The construct like

path=`dirname $0` works fine for a script being executed. For the
sourced one, $0 is set to your current shell name, say -bash ...

A solution for both bash and csh would be desired.



1. Determining full path of shell script in script

->> I am writing a Bourne shell script that needs to determine the full path
->> of itself.  In other words, if the script is /usr/local/bin/testme, I need
->> to determine that it resides in /usr/local/bin.
->> There is probably an easy and obvious answer to this, but it escapes me.
->> Checking $0 is useless, as a user may start the script using "./testme"
->> or any variant of "../../testme", etc.  "pwd" is also of no help.

->Can't think of a total no-brainer, but I think you're on the right track
->with $0.  Just use a conditional.  $0 either specifies an absolute path or a
->relative path (or no path).  Just test the leading character (/=absolute,
->anything else=relative).  If it's absolute, just use it.  If it's relative,
->just prepend the current working directory.  Remember that paths like
->"/abc/def/../../xyz" and "/abc/def/./xyz" are legal...

How about using which command:

ExeName=`which $0`

                                      /-------------------\    ^~~~~^
                                      |TECHNOLOGY         |    |    |
                                      |No place for wimps |   o|-OO-|o
                                      |          -Dilbert |--- | () |
                                      \-------------------/    |    |
Hemant Shah                      |  I haven't lost my mind,
LIDP, Inc.                       |  it's backed up on tape somewhere.
Voice: (708) 960 0133 Ext: 64    |
Fax: (708) 960 0717              |

WWW:   |

2. ES688:sound input directly couples back to output!

3. Sourcing a csh script from a ksh script

4. ksh(1): typeset -F ?

5. How to "source" a csh script from ksh script

6. Linux on Motorola LoPEC

7. Can you get the name of the calling prg/script from sh script

8. Trouble with Soundblaster 32 PnP ISA on FreeBSD 4.3

9. Shell script acting as interactive shell - $0 not script name??

10. Getting script file name and path?

11. How to modify path-name in csh script?

12. Accessing a shell script w/o doing . /script

13. abs. path names in script runs faster?