Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show line number when executing bash script

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.

like image 210
dspjm Avatar asked Jul 23 '13 07:07

dspjm


People also ask

How do I show line numbers in bash?

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 .

How do I show line numbers in shell script?

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.

How do you show the line number in a string in Linux?

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.

How do I print a line in bash?

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.


1 Answers

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]}(): }' 
like image 177
devnull Avatar answered Sep 28 '22 08:09

devnull