关于调试陷阱的问题

关于调试陷阱的问题

我有一个脚本如下:

function dbgtrap {
echo "badvar is $badvar" 
}

badvar=0

function some_func {
    badvar=1
    badvar=2
    badvar=3
}

set -o functrace

trap dbgtrap DEBUG
    some_func
trap - DEBUG    # turn off the DEBUG trap

获取脚本后,我得到了输出:

badvar is 0
badvar is 0
badvar is 0
badvar is 1
badvar is 2
badvar is 3

我期待着这样的事情:

badvar is 0
badvar is 1
badvar is 2
badvar is 3

输出的前两行来自哪里?

答案1

设置后,每个命令行都会调用该陷阱。如下图所示,使用 TRACE 输出:

+ badvar=0
+ set -o functrace
+ trap dbgtrap DEBUG
++ dbgtrap
++ echo 'badvar is 0'
badvar is 0
+ some_func
++ dbgtrap
++ echo 'badvar is 0'
badvar is 0
++ dbgtrap
++ echo 'badvar is 0'
badvar is 0
+ badvar=1
++ dbgtrap
++ echo 'badvar is 1'
badvar is 1
+ badvar=2
++ dbgtrap
++ echo 'badvar is 2'
badvar is 2
+ badvar=3
++ dbgtrap
++ echo 'badvar is 3'
badvar is 3
+ trap - DEBUG

IIRC shell 在处理结束时调用陷阱,因此在函数调用输出 badvar 值之前有 3 行输出。

相关内容