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

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

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 :
  if [ -N "$LOGFILE" ]; then
    echo "$(date): New entries in $LOGFILE:"
    newlen=$(wc -l "$LOGFILE" | awk '{ print $1 }')
    tail -"$(("$newlines"+1))" "$LOGFILE"