运用
PS4=':$LINENO+'
将行号添加到set -x的输出.
如果您只想在错误上打印它,那么在最近的解释器中存在一些遇到错误的风险.但是,您可以尝试以下操作(首先在this previous answer中给出):
error() {
local parent_lineno="$1"
local message="$2"
local code="${3:-1}"
if [[ -n "$message" ]] ; then
echo "Error on or near line ${parent_lineno}: ${message}; exiting with status ${code}"
else
echo "Error on or near line ${parent_lineno}; exiting with status ${code}"
fi
exit "${code}"
}
trap 'error ${LINENO}' ERR
同样,这不适用于最近的一些bash版本,它们并不总是在陷阱中正确设置LINENO.
另一种方法(仅适用于最近的shell;下面使用一些bash 4.0和4.1功能)是使用PS4将每个命令的退出状态和行号发送到专用文件描述符,并使用tail仅打印最后一个在shell退出之前给予该FD的行:
exec {BASH_XTRACEFD}> >(tail -n 1) # send set -x output to tail -n 1
PS4=':At line $LINENO; prior command exit status $?+'
set -x