Weird behaviour of $BASH_SOURCE

我的未来我决定 提交于 2019-12-31 02:20:15

问题


If you have foo.sh that declares a global function:

myfunction(){ echo $*;}
declare -fx myfunction

And you source it:

. foo.sh

And then you call the global function from bar.sh:

myfunction $BASH_SOURCE
myfunction a b c
myfunction $BASH_SOURCE

The third call produces a blank line, unless bar.sh is being sourced. Any ideas how to bypass this problem?


回答1:


Weird, this definitely looks like a bug. Possibly related to bash's shell function importing mechanism (when a shell function is found serialized in the environment and deserialized into the new process).

I just found that if you source foo.sh from inside bar.sh then the bug disappears:

. foo.sh
myfunction ${BASH_SOURCE[@]}
myfunction a b c
myfunction ${BASH_SOURCE[@]}

results in output

> ./bar.sh
./bar.sh
a b c
./bar.sh



回答2:


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".

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.



来源:https://stackoverflow.com/questions/27880087/weird-behaviour-of-bash-source

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!