Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the line number of a shell script error

When I run the script I get this error

awk: fatal: cannot open file `text.txt' for reading (No such file or directory)

The problem is the script is about 450 lines and it's really hard to find exactly where it's talking about

It would be great if I could just get a line number like

awk: fatal: cannot open file `text.txt' for reading (No such file or directory) at line ***

Or if I set -x then just

awk: fatal: cannot open file `text.txt' for reading (No such file or directory)
Terminated at line ***
like image 947
Sam Avatar asked Jul 06 '16 22:07

Sam


1 Answers

To add line numbers to bash -x output:

PS4='$LINENO:' bash -x  script

For complex cases where scripts call one another, it can be handy to know not just the line number but also the file name:

PS4='$BASH_SOURCE:$LINENO:' bash -x  script

PS4 can be further customized as you please. For example:

PS4='File=$BASH_SOURCE: LineNo=$LINENO: ' bash -x  script

Filtering the output

If we know what error message we are looking for, we can filter the output to get just that message and its corresponding file name and line number:

$ PS4='File=$BASH_SOURCE: LineNo=$LINENO: ' bash -x  script 2>&1 | grep -B1 'awk: fatal:'
File=script: LineNo=3: awk 1 text.txt
awk: fatal: cannot open file `text.txt' for reading (No such file or directory)
like image 117
John1024 Avatar answered Nov 07 '22 06:11

John1024