There are no solution that will work equally good in all flavours of shells.
In bash
you can use BASH_SOURCE
:
$(dirname "$BASH_SOURCE")
Example:
$ cat /tmp/1.sh
. /tmp/sub/2.sh
$ cat /tmp/sub/2.sh
echo $BASH_SOURCE
$ bash /tmp/1.sh
/tmp/sub/2.sh
As you can see, the script prints the name of 2.sh
,
although you start /tmp/1.sh
, that includes 2.sh
with the source
command.
I must note, that this solution will work only in bash
. In Bourne-shell (/bin/sh
) it is impossible.
In csh/tcsh/zsh you can use $_
instead of BASH_SOURCE
.