网络知识 娱乐 自动化工具-监测文件的变化

自动化工具-监测文件的变化

博客主页:https://tomcat.blog.csdn.net
博主昵称:农民工老王
主要领域:Java、Linux、K8S
期待大家的关注💖点赞👍收藏⭐留言💬
家乡

目录

  • 代码
  • 使用方法

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

代码

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

#!/bin/bash
# ------------------------------------------
# Filename    : fileTracer.sh
# Version     : 1.1
# Date        : 2022-5-21 23: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 "33[35m${timeStr}33[0m 33[36m[DEBUG]33[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的文件变化。

测试结果请见下面的视频:


如需转载,请注明本文的出处:农民工老王的CSDN博客https://blog.csdn.net/monarch91 。