bash 在执行shell脚本时,如何知道它正在执行的行号,

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10813863/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 02:24:48  来源:igfitidea点击:

While executing shell scripts, how to know which line number it's executing,

bashshell

提问by anish

While executing shell scripts, how to know which line number it's executing, do have write a wrapper , where i can execute a shell scripts from a shell scripts and to know which line number it's executing.

在执行 shell 脚本时,如何知道它正在执行的行号,确实编写了一个包装器,我可以在其中从 shell 脚本执行 shell 脚本并知道它正在执行的行号。

回答by Charles Duffy

You can set the PS4variable to cause set -xoutput to include the line number:

您可以设置PS4变量以使set -x输出包含行号:

PS4=':${LINENO}+'
set -x

This will put the line number before each line as it executes:

这将在执行时将行号放在每行之前:

:4+command here
:5+other command

It's important to have some sigil character (such as a +in my examples) after your variable expansions in PS4, because that last character is repeated to show nesting depth. That is, if you call a function, and that function invokes a command, the output from set -xwill report it like so:

+在 中的变量扩展之后有一些符号字符(例如我的示例中的 a)很重要PS4,因为重复最后一个字符以显示嵌套深度。也就是说,如果您调用一个函数,并且该函数调用一个命令,则输出set -x将报告如下:

:3+++command run within a function called from a function
:8++command run within a function
:19+line after the function was called

If multiple files are involved in running your script, you might want to include the BASH_SOURCEvariable as opposed to only LINENO(assuming this really is a bash script, as opposed to /bin/sh-- be sure your script starts with #!/bin/bash!):

如果运行脚本涉及多个文件,则您可能希望包含BASH_SOURCE变量而不是仅包含变量LINENO(假设这确实是一个 bash 脚本,而不是/bin/sh-- 请确保您的脚本以#!/bin/bash!开头):

PS4=':${BASH_SOURCE}:${LINENO}+'
set -x

回答by Paused until further notice.

Bash has a special variable $LINENOwhich does what you want.

Bash 有一个特殊的变量$LINENO可以做你想要的。

#!/bin/bash
echo "$LINENO"
echo "$LINENO"
echo "$LINENO"

Demo:

演示:

$ ./lineno
2
3
4

回答by Brian Agnew

#!/bin/sh -x

will report the lines as they're executed (the -xoption, to be clear). It won't give you the line number, but report the actual line.

将在执行时报告这些行(-x选项,要清楚)。它不会给你行号,而是报告实际的行。

An alternative, but more painful, approach is to use a trap handler, as documented here.

另一种但更痛苦的方法是使用陷阱处理程序,如此处所述