Bash – How to check which line of a bash script is being executed

bashmonitoringshell-script

Is there a way to check which line number of a bash script is being executed "right now"?

Using bash -x script.sh looks promising; however, I need to get the current line number.

Best Answer

Combine xtrace with PS4 inside the script:

$ cat test.sh 
#!/usr/bin/env bash
set -x
PS4='+${LINENO}: '

sleep 1m
sleep 1d
$ timeout 5 ./test.sh
+3: PS4='+${LINENO}: '
+5: sleep 1m

or in the parent shell:

$ cat test.sh 
sleep 1m
sleep 1d
$ export PS4='+${LINENO}: '
$ timeout 5 bash -x ./test.sh
+1: sleep 1m
Related Question