Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

ksh

pathname

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

like image 842
Dan Avatar asked Dec 05 '22 03:12

Dan


2 Answers

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.

like image 65
Ignacio Vazquez-Abrams Avatar answered Dec 30 '22 14:12

Ignacio Vazquez-Abrams


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

like image 44
Dana Lacoste Avatar answered Dec 30 '22 13:12

Dana Lacoste