shell 脚本调试
shell 脚本每一行执行之前的时候,会产生3个违信号,EXIT、ERR、DEBUG.
利用DEBUG可以监控执行的分支及过程。
trap 命令可以捕获指定的信号
trap 'command' signal
#! /bin/bash
trap 'echo "before execute line:$LINENO ,a=$a,b=$b,c=$c"' DEBUG
a=1
if [ "$a" -eq 1 ] ;then
b=2
else
b=1
fi
c=3
echo "end"
chmod +x file 保存后
执行结果
===========================
before execute line:5 ,a=,b=,c=
before execute line:6 ,a=1,b=,c=
before execute line:7 ,a=1,b=,c=
before execute line:11 ,a=1,b=2,c=
before execute line:12 ,a=1,b=2,c=3
end
===========================
需要注意的是,注释,空行,trap 命令本身,then ,else ,fi 等语句不会触发DEBUGE 信号。