How do you find the line number in Bash where an error occurred?
Example
I create the following simple script with line numbers to explain what we need. The script will copy files from
cp $file1 $file2
cp $file3 $file4
When one of the cp
commands fail then the function will exit with exit 1. We want to add the ability to the function to also print the error with the line number (for example, 8 or 12).
Is this possible?
Sample script
1 #!/bin/bash
2
3
4 function in_case_fail {
5 [[ $1 -ne 0 ]] && echo "fail on $2" && exit 1
6 }
7
8 cp $file1 $file2
9 in_case_fail $? "cp $file1 $file2"
10
11
12 cp $file3 $file4
13 in_case_fail $? "cp $file3 $file4"
14
set -x
and/orset -v
to trace what has been executed. Not exactly what you asked for but it will probably be helpful, too. – Rolf Aug 23 '18 at 08:34