Tail of the most recent file

I have a program that writes its output to a * .out file at startup. I installed a bash script to run several different times, so each run writes to a different * .out file. I found that I could tail most recent * .out file as follows:

 watch tail $(ls -tr *.out | tail -n1) 

The problem is that the $() link is executed only once. Therefore, when the first start is completed, watch continues to tail the same * .out file, although now there is a new * .out file.

How can I change this to go to the next * .out file after completing one run?

I tried to make some nesting of quotes and parentheses, but I do not quite understand the details of the links. Questions are complicated by the fact that watch passes its command to sh , although I use bash.

Bonus points: it would be great if it could be changed to tail -f instead of just repeating watch every n seconds.

+5
source share
3 answers

I also looked at this problem and finally came up with this solution:

  watch "ls -t1 | sed q | xargs tail" 

You need to hack a little bonus. The tail command also supports the --pid argument, which causes tail die as soon as the PID arrives. It sounds good? Here are some examples you could use:

 while true; do ls -t1 | sed q | xargs lsof -F np | sed 's/.\(.*\)/\1/g' | xargs tail -f --pid 2>/dev/null ; done 

This basically keeps track of the most current file and restarts tail when the file write process ends.

+2
source

So, I will repeat my current answer a little: Tail of the most recent file

you can use a very simple command to solve your problem:

 tail -f *.out 

tail works with multiple files, and it can be used like this:

 tail -f file1 file2 file3 

So, as you can see, this is a very powerful and simple tool, and you do not need to play with linux commands.

+1
source

If all files exist and you have a modern tail implementation that can handle multiple files,

 tail -f *.out 

would seem like a better solution. But if you don’t have all the files to start with, then it would still be easier if you just created them. *.out will only expand to files that you already have.

But if you cannot know the file names for tail -f before you start, you will need to restart the tail if any new files are created during your tail. In this case, given that you only write each outfile one at a time, you can do:

 inotifywait -m -e create -q . | while read dir event file; do kill %tail tail -f "$file" & done kill %tail 

(This requires inotifywait , which is included with inotify-tools on Debian-based systems such as Ubuntu.) It tracks the current directory for newly created files, tails depending on which file was created, in the background and kills the previous command tail whenever a new file is created.

+1
source

Source: https://habr.com/ru/post/1241282/


All Articles