Tailing Rolling Files

霸气de小男生 提交于 2019-12-03 10:27:32

You can use the -F option for tail which implies --follow=name --retry.

From the man page:

-F      
The -F option implies the -f option, but tail will also check to see if the 
file being followed has been renamed or rotated.  The file is closed and 
reopened when tail detects that the filename being read from has a new inode 
number. The -F option is ignored if reading from standard input rather than 
a file.

you may need inotify to detect the creation of the new file, a workaround for that would be to keep polling the filesystem while running tail on the background:

#!/bin/bash

get_latest() {
    local files=(*.log)
    local latest=${files[${#files[@]}-1]}
    echo "$latest"
    [[ $latest == $1 ]]
}
run_tail() {
    tail -c +0 -f "$1"
}

while true; do
    while current=$(get_latest "$current"); do
        sleep 1
    done
    [[ $pid ]] && kill $pid
    run_tail "$current" & pid=$!
done

(untested, unnecesarily hacky and be careful with the limitations of your old system!)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!