bash子shell执行函数时错误信息标注为environment的原因?
为什么Bash子shell中函数错误会标注为"environment"?
基础场景:直接执行cd命令
考虑以下简单的bash脚本:
cd nowhere
执行后得到如下错误信息:
my-script.sh: line 1: cd: nowhere: No such file or directory
这符合预期。
封装成函数执行
将cd命令封装到函数中:
function go_nowhere { cd nowhere; } go_nowhere
执行后错误信息与之前一致,合理。
子shell中直接执行cd命令
用子shell替代直接执行:
bash -c 'cd nowhere'
错误信息类似,但此时bash会以自身名称标识错误,而非脚本名称:
bash: line 1: cd: nowhere: No such file or directory
这依然符合预期。
子shell执行导出的函数
现在将两者结合:把cd命令封装到函数中,导出后在子shell中执行该函数:
function go_nowhere { cd nowhere; } export -f go_nowhere bash -c 'go_nowhere'
此时错误信息出现变化:行号变为“line 0”(因为子shell认为函数是从父进程继承的,定义在“第一行之前”),更奇怪的是错误标识变成了environment:
environment: line 0: cd: nowhere: No such file or directory
直接在子shell中定义函数执行
尝试直接在子shell命令中定义函数再执行,验证是否是环境继承导致的标识:
function go_nowhere { cd nowhere; } bash -c "`declare -f`; go_nowhere"
此时行号变为line 3,但错误信息仍标识为environment:
environment: line 3: cd: nowhere: No such file or directory
疑问
这个函数并非从环境继承而来,那字符串environment到底是从哪里来的?需要注意的是,这并非仅存在于脚本中,在交互式提示符下也能复现:子shell中函数内的错误会被标注为来自environment。
内容的提问来源于stack exchange,提问作者Mark VY
相关产品推荐
相关产品推荐

