How do you know you are on the last line when looping through a file?

What does it mean to be on the last line? It means that there are no lines after this one so one strategy would be to check if there is another line after the current one within the loop. If there isn't you are on the last line, otherwise you are in the middle.

Another technique would be to keep the line in a variable that is scoped outside the loop, then when the loop ends the variable contains the last line. This has the disadvantage of making the middle calculation incorrect but you could probably find a way around that.


Get the last line number of the file, also known as the total line count. Loop through the file, keeping track of the current line number. If the current line number equals the last line number, then do something.

#!/bin/bash

file="some-file.txt"
last_line=$(wc -l < $file)
current_line=0

while read -r line; do
  current_line=$(($current_line + 1))

  if [[ $current_line -ne $last_line ]]; then 
    # is NOT last line
  else
    # IS last line
  fi 
done < $file 

Tags:

Shell Script