Shell腳本實(shí)現(xiàn)監(jiān)測(cè)文件變化的示例詳解
我最近在使用Linux的過(guò)程中遇到,遇到這樣一個(gè)需求:監(jiān)測(cè)某個(gè)文件的創(chuàng)建,變動(dòng)、刪除,并記錄文件的每一個(gè)版本。我在網(wǎng)上沒(méi)有找到合適的腳本或工具,然后我就自己寫了一個(gè)shell腳本實(shí)現(xiàn)這個(gè)需求。
代碼
完整的shell腳本如下,可以直接使用。本示例中,腳本文件名為fileTracer.sh。
#!/bin/bash # ------------------------------------------ # Filename : fileTracer.sh # Version : 1.1 # Date : 2022-5-22 00:52:23 # Author: 農(nóng)民工老王@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 "文件被創(chuàng)建。" 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 "文件未創(chuàng)建。" elif [ $deleteNotice -eq 1 ]; then detection_log "文件被刪除。" fi deleteNotice=0 existNotice=1 fi flag=$((flag+1)) sleep ${sleepNum} done
使用方法
在腳本所在文件夾運(yùn)行:./fileTracer.sh ${監(jiān)測(cè)時(shí)長(zhǎng)} ${監(jiān)測(cè)間隔} ${被監(jiān)測(cè)文件的絕對(duì)路徑}
其中 監(jiān)測(cè)時(shí)長(zhǎng) 的單位為 分鐘,檢測(cè)間隔的單位為 秒,以上兩個(gè)參數(shù)均可以為小數(shù)。如:./fileTracer.sh 5 0.5 /root/test/poem.txt ,此指令表示在未來(lái)的5分鐘內(nèi),每隔0.5秒監(jiān)測(cè)一次 /root/test/poem.txt的文件變化。
到此這篇關(guān)于Shell腳本實(shí)現(xiàn)監(jiān)測(cè)文件變化的示例詳解的文章就介紹到這了,更多相關(guān)Shell監(jiān)測(cè)文件變化內(nèi)容請(qǐng)搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來(lái)源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來(lái)源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來(lái)源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來(lái),僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。