Skip to main content

Bash script to watch a log file and report only new entries.

#!/usr/bin/env bash

#
# Sometimes you want to read a file only if it has new content. A named pipe
# (also known as First In, First Out, or FIFO) could be a better solution, but
# sometimes you do not get to choose how the data is created. The `-N` flag
# tests if a file has been modified since it was last read. This can be
# demonstrated this with a pair of scripts --- in a graphical environment you
# can run this in two different windows; otherwise, use two separate sessions to
# the server.
#
# Orginal script from:
#   Wrox Shell Scripting expert recipeS for linux, BaSh, and More
#   http://www.wrox.com/WileyCDA/WroxTitle/Shell-Scripting-Expert-Recipes-for-Linux-Bash-and-more.productCd-1118024486.html
#

if [ -z "$1" ]; then
    echo "Usage: watchfile.sh <path>"
    exit 1
fi

UPDATE_INTERVAL=2  # how long to wait
LOGFILE=$1         # file to log to

# Get the current length of the file
len=$(wc -l "$LOGFILE" | awk '{ print $1 }')
echo "Current size is $len lines"

while :
do
  if [ -N "$LOGFILE" ]; then
    echo "$(date): New entries in $LOGFILE:"
    newlen=$(wc -l "$LOGFILE" | awk '{ print $1 }')
    newlines=$(("$newlen"-"$len"))
    tail -"$(("$newlines"+1))" "$LOGFILE"
    len=$newlen
  fi
  sleep $UPDATE_INTERVAL
done