>在
Linux上,你可以使用tail –follow = name(而不仅仅是-f,相当于–follow = descriptor)来实现你想要的,但是只有文件是DELETED而不是移动 – 一旦文件删除,报告错误消息并退出尾部(代码1);遗憾的是,相比之下,如果文件仅仅是MOVED(重命名),则tail不会退出 – 需要一个程序化的解决方案.
>在OSX上,您始终需要一个程序化解决方案 – 无论文件是移动还是删除.
一旦目标文件不再存在(以其原始名称)退出尾部的bash脚本 – 来自@ schellsan自己答案的更强大的脚本表达式:
#!/usr/bin/env bash
tail -f "$1" & # start tailing in the background
while [[ -f $1 ]]; do sleep 0.1; done # periodically check if target still exists
kill $! 2>/dev/null || : # kill tailing process,ignoring errors if already dead
>正确处理需要引用的文件名(例如,带有嵌入空格的名称).
>通过在文件存在检查之间休眠来防止创建紧密循环 – 根据需要调整睡眠持续时间;警告:一些平台只支持积分秒.
如果需要更强大的稳定性,这里有一个版本:
>通过退出陷阱杀死后台进程,以确保它被杀死,无论脚本本身如何退出(通常,或者说,通过Control-C).
>如果发现后台进程不再存在,则退出脚本.
#!/usr/bin/env bash
# Set an exit trap to ensure that the tailing process
# - to be created below - is terminated,# no matter how this script exits.
trap '[[ -n $tailPid ]] && kill $tailPid 2>/dev/null' EXIT
# Start the tailing process in the background and
# record its PID.
tail -f "$1" & tailPid=$!
# Stay alive as long as the target file exists.
while [[ -f $1 ]]; do
# Sleep a little.
sleep 0.1
# Exit if the tailing process died unexpectedly.
kill -0 $tailPid 2>/dev/null || { tailPid=; exit; }
done