How do I get `__FILE__` when sourcing a csh script
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 var开发者_开发问答s in the parent shell, I have to use source.
What to do?
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"
This is hard to read, but is actually works:
If your script is named test.csh
/usr/sbin/lsof +p $$ | \grep -oE /.\*test.csh
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'
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.
精彩评论