In bash2, how can I find the script name for the source?

Here is my situation:

I have several versions of the script in source control where the name differs by the path name component (for example: scc / project / 1.0 / script and scc / project / 1.1 / script). In another directory there is a symbolic link to one of these scripts. The name of the symbolic link is not associated with the name of the script, and in some cases may change periodically. This symbolic link, in turn, is used by bash using. command.

What I need to know: how to determine the directory of a reference script on a 10 year old system with bash 2 and Perl 5.5? For various reasons, the system must be used and cannot be updated.

In bash 3 or higher, I use this:

dir=`perl -MCwd=realpath -MFile::Basename 'print dirname(realpath($ARGV[0]))' ${BASH_SOURCE[0]} $0` 

Apologies for single-line Perl - it was originally a pure-Perl project with a very small amount of shell script.

I managed to get around the fact that the ancient Perl that I use does not export the "realpath" from Cwd, but unfortunately, bash 2.03.01 does not provide BASH_SOURCE or something like that, I could find. As a workaround, I provide the path information in a text file that I manually edit when I switch branches, but I really want this indicator to show which branch I use by myself.

Update: I apologize - apparently the question asked is not clear. Anyway, I don’t know how the name of the symbolic link will be displayed - what I am trying to figure out at runtime. The script is sometimes executed directly through a symbolic link, but more often than not, the link is an argument of "." . the command works in another script.

Also, $ 0 is not set properly when the script is sent via "." that is the whole problem I'm trying to solve. I apologize for the stupidity, but the decision, completely dependent on the set 0, is correct. In Perl's single-line box, I use BASH_SOURCE and $ 0 (BASH_SOURCE is set only when the script is sent via ".", So a single-line file uses only 0 if it is not received).

+4
source share
5 answers

Try using $0 instead of ${BASH_SOURCE[0]} . (No promises, I don't have bash 2 around.)

0
source

$0 has the name of the program / script that you are running.

0
source

Has it become normal? sort of

 stat -c %N $file 
0
source

bash cd and pwd inline functions have a -P option to allow symbolic links, so:

 dir=$(cd -P -- "$(dirname -- "$0")" && pwd -P) 

works with bash 2.03

0
source

I managed to get information that I used porcess sourcing my script using this command:

 ps -ef | grep $$ 

This is not ideal, but says that you want to process your script. It may be possible with some formation to determine the exact source.

0
source

All Articles