1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > linux删除文件退出 在Linux中用于在移动或删除文件时使`tail -f`退出的bash脚本

linux删除文件退出 在Linux中用于在移动或删除文件时使`tail -f`退出的bash脚本

时间:2023-12-22 17:11:44

相关推荐

linux删除文件退出 在Linux中用于在移动或删除文件时使`tail -f`退出的bash脚本

目前删除,移动或重命名在其上运行tail -f的文件什么都不做,我希望它能够中止.我已经阅读了手册页,似乎-f应该在文件移动时中止,-F将跟随文件,但在Mac OS X上似乎-f和-F是相同的.如何编写一个bash脚本,在文件移动后使tail -f完全退出?

>在

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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。