开发者

In bash2, how do I find the name of a script being sourced?

开发者 https://www.devze.com 2023-03-01 02:16 出处:网络
Here\'s my situation: I have multiple versions of a script in source code control where the name differs by a path name component (ex: scc/project/1.0/script and scc/project/1.1/script).In another di

Here's my situation:

I have multiple versions of a script in source code control where the name differs by a path name component (ex: scc/project/1.0/script and scc/project/1.1/script). In another directory, there is a symlink to one of these scripts. The symlink name is not related to the script name, and in some cases may change periodically. That symlink, in turn, is sourced by bash using the '.' command.

What I need to know: how do I determine the directory of the referenced script, on a 10 year-old system with Bash 2 and Perl 5.5? For various reasons, the system must be used, and it cannot be upgraded.

In Bash 3 or above, I use this:

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

Apologies for the Perl one-liner - this was originally a pure-Perl project with a very small amount o开发者_运维百科f shell script glue.

I've been able to work around the fact that the ancient Perl I am using doesn't export "realpath" from Cwd, but unfortunately, Bash 2.03.01 doesn't provide BASH_SOURCE, or anything like it that I've been able to find. As a workaround, I'm providing the path information in a text file that I change manually when I switch branches, but I'd really like to make this figure out which branch I'm using on its own.

Update: I apologize - apparently, the question as asked is not clear. I don't know in every case what the name of the symlink will be - that's what I'm trying to find out at run time. The script is occasionally executed via the symlink directly, but most often the link is the argument to a "." command running in another script.

Also, $0 is not set appropriately when the script is sourced via ".", which is the entire problem I'm trying to solve. I apologize for bluntness, but no solution that depends entirely upon $0 being set is correct. In the Perl one-liner, I use both BASH_SOURCE and $0 (BASH_SOURCE is only set when the script is sourced via ".", so the one-liner only uses $0 when it's not sourced).


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


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


Is stat ok? something like

stat -c %N $file


bash's cd and pwd builtins have a -P option to resolve symlinks, so:

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

works with bash 2.03


I managed to get information about the porcess sourcing my script using this command:

ps -ef | grep $$

This is not perfect but tells your which is the to process invoking your script. It migth be possible with some formating to determine the exact source.

0

精彩评论

暂无评论...
验证码 换一张
取 消