Shell腳本實現(xiàn)監(jiān)測文件變化的示例詳解
我最近在使用Linux的過程中遇到,遇到這樣一個需求:監(jiān)測某個文件的創(chuàng)建,變動、刪除,并記錄文件的每一個版本。我在網(wǎng)上沒有找到合適的腳本或工具,然后我就自己寫了一個shell腳本實現(xiàn)這個需求。
代碼
完整的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
使用方法
在腳本所在文件夾運行:./fileTracer.sh ${監(jiān)測時長} ${監(jiān)測間隔} ${被監(jiān)測文件的絕對路徑}
其中 監(jiān)測時長 的單位為 分鐘,檢測間隔的單位為 秒,以上兩個參數(shù)均可以為小數(shù)。如:./fileTracer.sh 5 0.5 /root/test/poem.txt ,此指令表示在未來的5分鐘內(nèi),每隔0.5秒監(jiān)測一次 /root/test/poem.txt的文件變化。
到此這篇關(guān)于Shell腳本實現(xiàn)監(jiān)測文件變化的示例詳解的文章就介紹到這了,更多相關(guān)Shell監(jiān)測文件變化內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
shell腳本中整數(shù)型變量自增(加1)的幾種實現(xiàn)
本文主要介紹了shell腳本中整數(shù)型變量自增(加1)的幾種實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-05-05