垃圾站 生活小记 Shell脚本实现监测文件变化的示例详解

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

我最近在使用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 "3[35m${timeStr}3[0m 3[36m[DEBUG]3[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脚本实现监测文件变化的示例详解插图

上一篇
下一篇
联系我们

联系我们

返回顶部