如何退出 tail -f 并恢复脚本

Ole*_*tov 3 linux bash tail

我有一个简单的脚本,它设置日志记录,tail -f在日志文件上运行,然后在退出后tail执行一些清理。基本上是这样的

echo 'monitoring started'
tail -f /var/log/some.log
echo 'never gets here'
Run Code Online (Sandbox Code Playgroud)

问题是,tail按 Ctrl+C 退出也会中断脚本执行,因此不会调用清理。有没有办法“正确”退出tail并恢复脚本调用?我找到了一些基于保存PID并通过超时杀死它的解决方案,但这不是我想要的,我可能需要监控几分钟或几个小时,所以我想要一个手动切换。

S.K*_*ers 5

你可以做这样的事情

echo "monitoring started"
tail -f /var/log/some.log & #execute tail in background
read -sn 1 #wait for user input
kill %1 #kill the first background progress, i.e. tail
echo "Is reached"
Run Code Online (Sandbox Code Playgroud)