Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a ksh script determine the full path to itself, when sourced from another?

Tags:

ksh

How can a script determine it's path when it is sourced by ksh? i.e.

$ ksh ". foo.sh"

I've seen very nice ways of doing this in BASH posted on stackoverflow and elsewhere but haven't yet found a ksh method.

Using "$0" doesn't work. This simply refers to "ksh".

Update: I've tried using the "history" command but that isn't aware of the history outside the current script.

$ cat k.ksh
#!/bin/ksh
. j.ksh
$ cat j.ksh
#!/bin/ksh
a=$(history | tail -1)
echo $a
$ ./k.ksh
270 ./k.ksh

I would want it echo "* ./j.ksh".

like image 700
mathtick Avatar asked Sep 30 '11 21:09

mathtick


2 Answers

If it's the AT&T ksh93, this information is stored in the .sh namespace, in the variable .sh.file.

Example

sourced.sh:

(
 echo "Sourced: ${.sh.file}"
)

Invocation:

$ ksh -c '. ./sourced.sh'

Result:

Sourced: /var/tmp/sourced.sh

The .sh.file variable is distinct from $0. While $0 can be ksh or /usr/bin/ksh, or the name of the currently running script, .sh.file will always refer to the file for the current scope.

In an interactive shell, this variable won't even exist:

$ echo ${.sh.file:?}
-ksh: .sh.file: parameter not set
like image 171
Henk Langeveld Avatar answered Sep 28 '22 13:09

Henk Langeveld


I believe the only portable solution is to override the source command:

source() {
  sourced=$1
  . "$1"
}

And then use source instead of . (the script name will be in $sourced).

like image 22
Dimitre Radoulov Avatar answered Sep 28 '22 12:09

Dimitre Radoulov