我最近在使用Linux的过程中遇到,遇到这样一个需求:监测某个文件的创建,变动、删除,并记录文件的每一个版本。我在网上没有找到合适的脚本或工具,然后我就自己写了一个shell脚本实现这个需求。
代码
完整的shell脚本如下,可以直接使用。本示例中,脚本文件名为fileTracer.sh。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
|
#!/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监测文件变化内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://blog.csdn.net/monarch91/article/details/124908145