执行bash脚本时如何显示行号 [英] How to show line number when executing bash script

查看:57
本文介绍了执行bash脚本时如何显示行号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个测试脚本,它有很多命令并且会产生很多输出,我使用 set -xset -vset -e,所以脚本会在发生错误时停止.但是,我仍然很难找到执行停止的哪一行以定位问题.有没有一种方法可以在执行每一行之前输出脚本的行号?还是输出set -x生成的命令展前的行号?或者任何可以处理我的脚本行位置问题的方法都会有很大帮助.谢谢.

I have a test script which has a lot of commands and will generate lots of output, I use set -x or set -v and set -e, so the script would stop when error occurs. However, it's still rather difficult for me to locate which line did the execution stop in order to locate the problem. Is there a method which can output the line number of the script before each line is executed? Or output the line number before the command exhibition generated by set -x? Or any method which can deal with my script line location problem would be a great help. Thanks.

推荐答案

您提到您已经在使用 -x.变量PS4表示该值是设置-x选项时回显命令行前打印的提示,默认为:后跟空间.

You mention that you're already using -x. The variable PS4 denotes the value is the prompt printed before the command line is echoed when the -x option is set and defaults to : followed by space.

您可以更改 PS4 以发出 LINENO(当前正在执行的脚本或 shell 函数中的行号).

You can change PS4 to emit the LINENO (The line number in the script or shell function currently executing).

例如,如果您的脚本如下:

For example, if your script reads:

$ cat script
foo=10
echo ${foo}
echo $((2 + 2))

因此执行它会打印行号:

Executing it thus would print line numbers:

$ PS4='Line ${LINENO}: ' bash -x script
Line 1: foo=10
Line 2: echo 10
10
Line 3: echo 4
4

http://wiki.bash-hackers.org/scripting/debuggingtips 给出了终极的PS4 会输出你追踪可能需要的一切:

http://wiki.bash-hackers.org/scripting/debuggingtips gives the ultimate PS4 that would output everything you will possibly need for tracing:

export PS4='+(${BASH_SOURCE}:${LINENO}): ${FUNCNAME[0]:+${FUNCNAME[0]}(): }'

这篇关于执行bash脚本时如何显示行号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆