I have a directory full of log files and I would like a bash oneline command to follow the latest log file that matches a pattern (e.g. "logfile*"). Basically I have a line that should work, just it does not...
tail -f $(ls -1rt logfile* | tail -n 1)
When I test only part of the command like so
ls -1rt logfile* | tail -n 1
logfile_20210111_105242.log
It will give me the latest log filename that I want to follow:
but adding the tail -f
I get following response:
tail -f $(ls -1rt logfile* | tail -n 1)
tail: cannot open ''$'\033''[0m'$'\033''[00mlogfile_20210111_105242.log'$'\033''[0m' for reading: No such file or directory
Any ideas on how to get this to work?
EDIT: Also, any idea how best to use this in an alias with parameters? most reasearch indicates a function in .bashrc
has to be used, but I also found someone saying it should be possible by using !:1
as variables.
EDIT2: Solution
Step1: use the solution from comments below
tail -f $(find . -maxdepth 1 -name 'logfile*' -printf '%Ts/%f\n' | sort -n | tail -1 | cut -d/ -f2)
Step2: put it in .alias
and make it work with a paramter for a filepattern
alias tailf="tail -f $(find . -maxdepth 1 -name '\!:1' -printf '%Ts/%f\n' | sort -n | tail -1 | cut -d/ -f2)"
EDIT3: While the alias seems to work, unfortunately it will tail all files matching the pattern passed as parameter. When I hardcode the pattern in the alias definition it works perfectly just tailing the latest file matching the pattern.
Thanks
tail -f "$(find . -maxdepth 1 -name "logfile*" -printf "%Ts/%f\n" | sort -n | tail -1 | cut -d/ -f2)"
Tail the result of the find command. Search for files prefixed with logfile in the current directory and print the epoch time of creation as well as the file path and name, separated by a forward slash Pipe this through to sort and then print the latest entry with tail -1 before stripping out to to leave only the file path with cut.