目前删除,移动或重命名运行tail -f
的文件什么都不做,我希望它能够中止。我已经阅读了手册页,似乎-f应该在文件移动时中止,-F将跟随文件,但在Mac OS X上似乎-f和-F是相同的。如何编写一个bash脚本,在文件移动后使tail -f完全退出?
答案 0 :(得分:7)
tail --follow=name
(而不仅仅是-f
,相当于--follow=descriptor
)来实现您的目标,但仅限于该文件是删除而不是移动 - 删除文件后,将报告错误消息并退出tail
(代码为1);遗憾的是,相比之下,如果文件只是MOVED(重命名),tail
不会退出 - 需要一个程序化的解决方案。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
如果需要更强大,那么这是一个版本:
#!/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
答案 1 :(得分:1)
以防万一其他人遇到此问题,您可以使用一个小脚本,在其中运行tail作为后台进程,然后循环直到文件被移动,从而终止尾部进程。
#!/bin/bash
tail -f $1 &
pid=$!
while [ -f $1 ]
do
if [ ! -f $1 ]
then
kill -9 $pid
fi
done