获取 csh 脚本时如何获取 `__FILE__`

发布于 2024-10-05 06:45:44 字数 193 浏览 1 评论 0原文

我有一个脚本,用于在调用 csh shell 中设置一些环境变量。其中一些变量取决于脚本的位置。

如果该文件是正确的 csh 脚本,我可以使用 $0 访问 __FILE__ 但如果我使用源运行该脚本,它只会告诉我 csh 或 tcsh。

由于我使用它在父 shell 中设置变量,因此我必须使用 source。

该怎么办?

I have a script that is used to set some env vars in the calling csh shell. Some of those variables depend on the location of the script.

If the file is a proper csh script, I can use $0 to access __FILE__ but if I run the script using source, it just tells me csh or tcsh.

Since I'm using this to set vars in the parent shell, I have to use source.

What to do?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

你列表最软的妹 2024-10-12 06:45:44

如果您在文件的第一行访问 $_ ,它将包含文件的名称(如果它是来源的)。如果直接运行,则 $0 将包含名称。

#!/bin/tcsh
set called=($_)
if ($called[2] != "") echo "Sourced: $called[2]"
if ($0 != "tcsh") echo "Called: $0"

If you access $_ on the first line of the file, it will contain the name of the file if it's sourced. If it's run directly then $0 will contain the name.

#!/bin/tcsh
set called=($_)
if ($called[2] != "") echo "Sourced: $called[2]"
if ($0 != "tcsh") echo "Called: $0"
靖瑶 2024-10-12 06:45:44

这很难阅读,但实际上是有效的:

如果您的脚本名为 test.csh

/usr/sbin/lsof +p $$ | \grep -oE /.\*test.csh

This is hard to read, but is actually works:

If your script is named test.csh

/usr/sbin/lsof +p $$ | \grep -oE /.\*test.csh

傲性难收 2024-10-12 06:45:44

这个答案描述了 lsof 和一点 grep 魔法似乎是唯一站得住脚的东西有机会处理 csh/tcsh 下的嵌套源文件。

如果您的脚本名为 source_me.tcsh

/usr/sbin/lsof -p $ | grep -oE '/.*source_me\.tcsh'

this answer describes how lsof and a bit of grep magic is the only thing that seems to stand a chance of working for nested sourced files under csh/tcsh.

If your script is named source_me.tcsh:

/usr/sbin/lsof -p $ | grep -oE '/.*source_me\.tcsh'
岁月静好 2024-10-12 06:45:44

当在子 shell 中调用源代码时,$$ 不起作用。 BASH_PID 仅适用于 bash。

% (sleep 1; source source_me.csh)

我发现以下方法效果更好一些:

% set pid=`cut -d' ' -f4 < /proc/self/stat`
% set file=`/usr/sbin/lsof +p $pid|grep -m1 -P '\s\d+r\s+REG\s' | xargs | cut -d' ' -f9`

第一行查找正在获取文件的当前进程的 pid。这来自 为什么 $$ 返回与父进程的 id 相同?。第二行找到第一个(希望是唯一的)为读取常规文件而打开的 FD。这来自上面的 engtech。

The $$ does not work when one calls the source within a sub-shell. BASH_PID only works in bash.

% (sleep 1; source source_me.csh)

I found the following works a bit better:

% set pid=`cut -d' ' -f4 < /proc/self/stat`
% set file=`/usr/sbin/lsof +p $pid|grep -m1 -P '\s\d+r\s+REG\s' | xargs | cut -d' ' -f9`

First line finds the pid of the current process that is sourcing the file. This came from Why is $$ returning the same id as the parent process?. The second line finds the first (and hopefully only) FD opened for read of a regular file. This came from engtech above.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文