How to get the full path to the current shell script?

Is there any way more brute force to do this?

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

I am stuck with ksh , but would prefer a solution that works in bash too (which I think is the case).

+4
source share
3 answers

Entry # 28 in the bash FAQ:

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

There are two main reasons why this problem occurs: either you want to export the data or configuration of your script, and look for a way to find these external resources, or your script is designed to work on the set (for example, build a script), and it needs to find resources to work .

It is important to understand that in general this problem has no solution. Any approach that you may have heard about, and any approach that will be described in detail below, has drawbacks and will only work in specific cases. First of all, try to completely avoid the problem, regardless of the location of your script!

...

Using BASH_SOURCE

The bash internal variable BASH_SOURCE is actually an array of paths. If you expand it as a simple string, for example. "$ BASH_SOURCE" you will get the first element, which is the name of the current executable function or script.

+5
source

I always did:

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

I have never used readlink before: is it just Gnu? (i.e. will it work with HP-UX, AIX and Solaris from the window? dirname and pwd will be ...)

(edited to add `` which I forgot in the original post. d'oh!) (edit 2 to put two lines, which I apparently always did when I looked at the previous scripts that I wrote, but not remembered correctly. The first call gets the path, the second call excludes the relative path) (edit 3 fixed typos that prevent one line answer from working, back to one line!)

+5
source

Why didn’t I think to try this before I asked a question?

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

It works great.

+4
source

Source: https://habr.com/ru/post/1304396/


All Articles