Skip to content
Advertisement

tail the last modified file and monitor for new files in bash

I can tail -f the last modified file using ls --sort=time | head -1 | xargs tail -f but I’m looking for something that would continuously run the first part as well, i.e. if a new files is created while the tail command is running it switches to tailing the new file. I thought about using watch command but that doesn’t seem to work nicely with tail -f

Advertisement

Answer

It seems you need something like this:

#!/bin/bash

TAILPID=0
WATCHFILE=""

trap 'kill $(jobs -p)' EXIT     # Makes sure we clean our mess (background processes) on exit

while true
do
    NEWFILE=`ls --sort=time | head -n 1`
    if [ "$NEWFILE" != "$WATCHFILE" ]; then

            echo "New file has been modified"
            echo "Now watching: $NEWFILE";
            WATCHFILE=$NEWFILE
            if [ $TAILPID -ne 0 ]; then
                    # Kill old tail
                    kill $TAILPID
                    wait $! &> /dev/null # supress "Terminated" message 
            fi
            tail -f $NEWFILE &
            TAILPID=$!      # Storing tail PID so we could kill it later
    fi
    sleep 1
done
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement