Print out Line Numbers in a BASH Script

The environment variable $LINENO contains the current line number of the running BASH shell. On the command line the value will be the number of command line prompts you've used in that shell, but in a script it's the currently executing line -- and it really is line number, if you loop over the same lines it will continue to print the same line number.


echo $0 $LINENO: 3

for I in one two three; do
    echo $0 $LINENO: $I in loop

echo $0 $LINENO: 9, on same line; echo $0 $LINENO: 9, on same line

( echo $0 $LINENO: 11, in subshell ) 

function f {
    echo $0 $LINENO: 14, function


This example script will produce the following output:

./ 3: 3
./ 6: one in loop
./ 6: two in loop
./ 6: three in loop
./ 9: 9, on same line
./ 9: 9, on same line
./ 11: 11, in subshell
./ 14: 14, function

Useful for more fine tuned debugging (instead of something like bash -x), or giving context to error messages.