新闻动态

Shell脚本实现监测文件变化的示例详解

发布日期:2022-07-20 19:43 | 文章来源:gibhub

我最近在使用Linux的过程中遇到,遇到这样一个需求:监测某个文件的创建,变动、删除,并记录文件的每一个版本。我在网上没有找到合适的脚本或工具,然后我就自己写了一个shell脚本实现这个需求。

代码

完整的shell脚本如下,可以直接使用。本示例中,脚本文件名为fileTracer.sh。

#!/bin/bash
# ------------------------------------------
# Filename : fileTracer.sh
# Version  : 1.1
# Date  : 2022-5-22 00:52:23
# Author: 农民工老王@CSDN
# Email : scwja@qq.com
# Website  : https://blog.csdn.net/monarch91
# Description : 用于追踪文件变化的脚本
# ------------------------------------------
time=$1
sleepNum=$2
filePath=$3
fileName=`basename ${filePath}`
whileNum=$(echo "scale=0;${time}*60/${sleepNum}"|bc)
flag=0
historyDir=./fileHistory
timeStr=""
detection_log() {
  timeStr=$(date "+%H:%M:%S.%N")
  timeStr=${timeStr:0:12}
  echo -e "\033[35m${timeStr}\033[0m \033[36m[DEBUG]\033[0m :$1"
}
existNotice=0
deleteNotice=0
md5StrLast=""
mkdir -p $historyDir
while [ $flag  -lt $whileNum ]; do
  if [ -f "${filePath}"  ]; then
 if [ $existNotice -eq  1 ] || [ $flag -eq 0 ] ; then
if [ $flag -eq 0 ]; then
  detection_log "文件已存在。"
else
  detection_log "文件被创建。"
fi
md5StrLast=`md5sum ${filePath} | awk '{ print $1 }'`
cp -fr ${filePath} ${historyDir}/${timeStr}_${fileName}
 else
md5StrNow=`md5sum ${filePath} | awk '{ print $1 }'` >/dev/null 2>&1
if [ "lw${md5StrNow}" != "lw" ] && [ "lw${md5StrNow}" != "lw${md5StrLast}" ]; then
detection_log "文件被修改。"
cp -fr ${filePath} ${historyDir}/${timeStr}_${fileName}
md5StrLast=${md5StrNow}
fi
 fi
 existNotice=0
 deleteNotice=1
  else
 if [ $flag -eq 0 ]; then
  detection_log "文件未创建。"
 elif [ $deleteNotice -eq 1 ]; then
  detection_log "文件被删除。"
 fi
 deleteNotice=0
 existNotice=1
  fi
  flag=$((flag+1))
  sleep ${sleepNum}
done

使用方法

在脚本所在文件夹运行:./fileTracer.sh ${监测时长} ${监测间隔} ${被监测文件的绝对路径}
其中 监测时长 的单位为 分钟,检测间隔的单位为 秒,以上两个参数均可以为小数。如:./fileTracer.sh 5 0.5 /root/test/poem.txt ,此指令表示在未来的5分钟内,每隔0.5秒监测一次 /root/test/poem.txt的文件变化。

到此这篇关于Shell脚本实现监测文件变化的示例详解的文章就介绍到这了,更多相关Shell监测文件变化内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!

国外稳定服务器

版权声明:本站文章来源标注为YINGSOO的内容版权均为本站所有,欢迎引用、转载,请保持原文完整并注明来源及原文链接。禁止复制或仿造本网站,禁止在非www.yingsoo.com所属的服务器上建立镜像,否则将依法追究法律责任。本站部分内容来源于网友推荐、互联网收集整理而来,仅供学习参考,不代表本站立场,如有内容涉嫌侵权,请联系alex-e#qq.com处理。

相关文章

实时开通

自选配置、实时开通

免备案

全球线路精选!

全天候客户服务

7x24全年不间断在线

专属顾问服务

1对1客户咨询顾问

在线
客服

在线客服:7*24小时在线

客服
热线

400-630-3752
7*24小时客服服务热线

关注
微信

关注官方微信
顶部