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.

#!/bin/bash

echo $0 $LINENO: 3

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

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
}

f

This example script will produce the following output:

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

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