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.
Bash Using cat Display line numbers with outputUse the --number flag to print line numbers before each line. Alternatively, -n does the same thing. To skip empty lines when counting lines, use the --number-nonblank , or simply -b .
Press the Esc key if you are currently in insert or append mode. Press : (the colon). The cursor should reappear at the lower left corner of the screen next to a : prompt. A column of sequential line numbers will then appear at the left side of the screen.
The -n ( or --line-number ) option tells grep to show the line number of the lines containing a string that matches a pattern. When this option is used, grep prints the matches to standard output prefixed with the line number.
Printing Newline in Bash The most common way is to use the echo command. However, the printf command also works fine. Using the backslash character for newline “\n” is the conventional way.
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.
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 gives the ultimate PS4
that would output everything you will possibly need for tracing:
export PS4='+(${BASH_SOURCE}:${LINENO}): ${FUNCNAME[0]:+${FUNCNAME[0]}(): }'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With