Bash如何获取文件绝对行号而非函数相对行号
在GNU Bash 5.2.15中获取函数调用的实际文件行号
现有Bash脚本示例如下,调用do_most后,caller命令输出的是函数内的相对行号(比如显示do_more调用do_something在第3行,实际是文件第28行),需要获取调用语句在文件中的实际行号,请问在Bash 5.2.15版本中是否有实现方法?
示例脚本:
some_function() { echo "here" } do_something () { local frame=0 local values=() while values=($(caller $frame)); do local fline=${values[0]} local fname=${values[1]} local fsource=${values[2]} echo "Line ${fline} of '${fname}' in file ${fsource}." ((frame++)) done echo "LINENO: $LINENO" echo "BASH_LINENO: ${BASH_LINENO[*]}" echo "FUNCNAME: ${FUNCNAME[*]}" echo "BASH_SOURCE: ${BASH_SOURCE[*]}" some_function } do_more () { # comment to change line numbering do_something } do_most () { do_more }
调用do_most后的当前输出:
Line 3 of 'do_more' in file test_lineno.sh. Line 2 of 'do_most' in file test_lineno.sh. LINENO: 12 BASH_LINENO: 3 2 200 FUNCNAME: do_something do_more do_most BASH_SOURCE: test_lineno.sh test_lineno.sh test_lineno.sh here
在Bash 5.0及以上版本(包括5.2.15),caller命令支持-l选项,使用该选项即可返回调用语句在文件中的实际绝对行号,而非函数内的相对行号。
修改do_something函数中的caller调用部分,添加-l参数:
while values=($(caller -l $frame)); do
修改后再次调用do_most,输出会变为类似:
Line 28 of 'do_more' in file test_lineno.sh. Line 33 of 'do_most' in file test_lineno.sh. LINENO: 12 BASH_LINENO: 3 2 200 FUNCNAME: do_something do_more do_most BASH_SOURCE: test_lineno.sh test_lineno.sh test_lineno.sh here
说明:
caller -l返回的第一个字段就是调用语句在文件中的绝对行号,替代了原有的相对行号BASH_LINENO数组仍会保留相对行号的数值,若仅需绝对行号,使用caller -l即可满足需求
内容的提问来源于stack exchange,提问作者AdamC
相关产品推荐
相关产品推荐

