Question

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).

Was it helpful?

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.

OTHER TIPS

I've always done:

SCRIPT_PATH=$(cd `dirname ${0}`; pwd)

I've never used readlink before: is it Gnu only? (i.e. will it work on HP-UX, AIX, and Solaris out of the box? dirname and pwd will....)

(edited to add `` which I forgot in original post. d'oh!) (edit 2 to put on two lines which I've apparently always done when I look at previous scripts I'd written, but hadn't remembered properly. First call gets path, second call eliminates relative path) (edit 3 fixed typo that prevented single line answer from working, back to single line!)

Why didn't I think to try this before I asked the question?

THIS_SCRIPT=$(/usr/bin/readlink -nf "$0")

Works great.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top