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

>在

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值