Bourne: $0 issues when sourcing files

Problem in simple script form:

File 1:

# cat test.sh
#!/bin/sh
echo "Running test.sh - \$0 is  $0"
echo "Sourcing test2.sh"
. ./test2.sh
exit

File 2 (Sourced file):

# cat test2.sh
#!/bin/sh
echo "Running test2.sh - \$0 is $0"
exit

Output:

# ./test.sh 
Running test.sh - $0 is  ./test.sh
Sourcing test2.sh
Running test2.sh - $0 is ./test.sh

In case it matters:

uname -a
SunOS a70sspalport001 5.10 Generic_147440-25 sun4v sparc SUNW,SPARC-Enterprise-T5120

The problem is that when I'm sourcing another script, that script reports $0 as the name of the parent script. I've found many answers where $BASH_SOURCE is the answer, however bash is not a shell I can use (ksh is an option, however). If this simply isn't something I can do, that's fine, and once my stuff all hits production it won't actually be so important, but in final stages of QA it's becoming a hassle.

Thanks in advance.

Edit: I've had multiple edits, as I thought I had a working hack, but I was incorrect...

If you have a modern Korn shell installed, ${.sh.file} should contain the name of the file that was sourced.

Have a try with something like this:

#!/usr/bin/env ksh
echo "Running test2.sh - ${.sh.file} sourced from $0"
exit

I think it goes without saying, but just to be sure, the parent script must be executed by Kshell, not Bourne shell.

The Kshell man page lists all of these useful variables:
man/man1/ksh.html man page

1 Like