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
Asked
Active
Viewed 354 times
2

Milad
- 4,901
- 5
- 32
- 43
-
1See http://superuser.com/questions/956311/continuously-detect-new-files-with-inotify-tools-within-multiple-directories-r – tripleee Mar 24 '16 at 11:39
1 Answers
3
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

DevilaN
- 1,317
- 10
- 21
-
This has the obvious problem that you are parsing `ls` and assuming that file names never contain a newline. A more robust solution would use `find` and, of course, [properly quote any variable](http://stackoverflow.com/questions/10067266/when-to-wrap-quotes-around-a-variable) which contains a file name. But this has been beaten to death many times; go look for duplicates. – tripleee Mar 24 '16 at 11:38