Skip to content
Advertisement

How to follow latest log file with tail -f?

I have a dir that saves a fresh log file for each run, so I use the following command to follow the latest log file:

tail -f $(ls -t | head -1)

So my question would be if there is any way to jump from one file to the next, if there is a newer log file available without having to stop the latest tail -f and rerunning it?

Advertisement

Answer

What you could attempt is something like this:

# setup a link that points to the youngest file    
$ for f in *; do [[  ( ! -f last )  || ( "$f" -nt last) ]] && ln -sf "$f" last; done
# monitor that file continuously by filename
$ tail -F last

run the following in another shell

while :; for f in *; do [ "$f" -nt last ] && ln -sf "$f" last; done

You can also run this in a single command as:

while :; do for f in *; do [[  ( ! -f last )  || ($f -nt last) ]] && ln -sf $f last; done; done & tail -F last
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement