9

I am looking for a way to print the line number of files my script is going through. I have found $LINENO but when I do

echo 'Found foo in file' $(basename $foo) 'on line' $LINENO >> foo.csv

It prints the results "Found foo in file Foo on line 97 in the .csv file. I would like it to print the line in the file it is looking at and not the line the script it is on. How can I echo the line number in the files?

3
  • what are you using to iterate through the lines of the file?
    – Matt
    Aug 23, 2013 at 15:56
  • I am using an if then. Aug 23, 2013 at 16:10
  • 1
    Could you show us the entire loop? That way we can give you a solution tailored to your needs.
    – terdon
    Aug 23, 2013 at 16:44

2 Answers 2

19

You can use nl to number the lines of the file before going through them:

$ cat testfile
a
b
c
$ nl -b a testfile
   1 a
   2 b
   3 c

Note that -b a is required because, by default, nl doesn't number blank lines.

Of course, this will be inefficient if your file is very large as it will go through the file twice.

Perhaps a better alternative is to use your own line counter so that you need only go through the file once:

COUNT=0
while read -r line; do
    COUNT=$(( $COUNT + 1 ))
    if [ ... ];then
        # Do things to the line
        # Make use of COUNT to show line number
    fi
done < your_file_here

This will only work if you're processing the file line-by-line. It won't work if you're using grep for example.

2
  • @GearoidMurphy - there's an infinite supply of these 8-)
    – slm
    Aug 23, 2013 at 16:04
  • It doesn't count empty lines even if I use option $ nl -ba app.d. If I add a white space the line is counted. That tool isn't that great.
    – chmike
    May 24, 2016 at 12:41
2

The way I've found to do this is to use trap DEBUG to store current line number to a secondary variable and trap ERR to dump them:

#!/bin/bash

trap 'LASTLINENO=$_LINENO;_LINENO=$LINENO' DEBUG
trap 'echo ERROR in file" $(basename $0) on line $LASTLINENO" >>logfile' ERR

echo test
test echo
bla

This will print on console:

test
./test.bash: line 8: bla: command not found

and store on logfile:

ERROR in file test.bash on line 8

For showing script:

cat -n test.bash
     1      #!/bin/bash
     2
     3      trap 'LASTLINENO=$_LINENO;_LINENO=$LINENO' DEBUG
     4      trap 'echo ERROR in file" $(basename $0) on line $LASTLINENO"' ERR
     5
     6      echo test
     7      test echo
     8      bla

And for showing desired (corrupted) line:

sed -ne 8p <test.bash
bla

Not the answer you're looking for? Browse other questions tagged .