$ BASH_SOURCE的怪异行为 [英] Weird behaviour of $BASH_SOURCE
问题描述
如果您有声明全局函数的foo.sh:
If you have foo.sh that declares a global function:
myfunction(){ echo $*;}
declare -fx myfunction
您就可以找到它:
. foo.sh
然后从bar.sh调用全局函数:
And then you call the global function from bar.sh:
myfunction $BASH_SOURCE
myfunction a b c
myfunction $BASH_SOURCE
第三个调用将产生一个空行,除非已获取bar.sh.有什么想法可以绕过这个问题吗?
The third call produces a blank line, unless bar.sh is being sourced. Any ideas how to bypass this problem?
推荐答案
根据bash手册, BASH_SOURCE
是一个数组,其每个元素都是与的相应元素相关联的文件名> FUNCNAME
,仅在执行Shell函数时存在".
According to the bash manual, BASH_SOURCE
is an array, each element of which is the filename associated with the corresponding element of FUNCNAME
, which "exists only when a shell function is executing".
因此,在函数调用之外的 BASH_SOURCE
中的任何值(且函数自变量的求值均在函数调用之外)都是未记录的用法;该变量当时没有记录的值.
So any value in BASH_SOURCE
outside of a function call (and the evaluation of function arguments are outside of a function call) is an undocumented use; the variable has no documented value at that point.
这篇关于$ BASH_SOURCE的怪异行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!