bashkshpathname

How to get the full pathname of the current shell script?


Is there a less brute-force way to do this?

#!/bin/ksh
THIS_SCRIPT=$(/usr/bin/readlink -f $(echo $0 | /bin/sed "s,^[^/],$PWD/&,"))
echo $THIS_SCRIPT

I'm stuck using ksh but would prefer a solution that works in bash too (which I think this does).


Solution

  • Entry #28 in the bash FAQ:

    How do I determine the location of my script? I want to read some config files from the same place.

    There are two prime reasons why this issue comes up: either you want to externalize data or configuration of your script and need a way to find these external resources, or your script is intended to act upon a bundle of some sort (eg. a build script), and needs to find the resources to act upon.

    It is important to realize that in the general case, this problem has no solution. Any approach you might have heard of, and any approach that will be detailed below, has flaws and will only work in specific cases. First and foremost, try to avoid the problem entirely by not depending on the location of your script!

    ...

    Using BASH_SOURCE

    The BASH_SOURCE internal bash variable is actually an array of pathnames. If you expand it as a simple string, e.g. "$BASH_SOURCE", you'll get the first element, which is the pathname of the currently executing function or script.