欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Shell脚本检查文件是否有改动

程序员文章站 2022-07-10 08:22:37
...

目的:检查某个文件夹及其子文件夹下的所有文件是否被改动。

思路:

1. 使用stat命令将所有文件的更改时间记录到文件A中。每个被扫描的文件在文件A中被记录为一行。

2. 然后定期检查所有文件的最新更改时间。并将最新的更改时间记录到一个新文件B中。与A一样,每一行会记录一个被扫描文件的最新更改时间。

3. 逐行比较文件A和文件B。若某行不一致,则说明该行所表示的被扫描文件有改动。将这一行打印出来。

#!/bin/bash
# 定时检查文件是否有更改,有更改就打印出更改的文件。

# scan the file tree
scanDir(){
  # one parameter
  for i in ` ls $1 | sed -e 's/ /\n/g' `;
  do
    # check if this is a dir.
    if [ -d $1/$i ];
    then
      # iterate to son dir.
      checkDir "$1/$i"
    else
      # print just for debug.
      echo "$1/$i"
    fi
  done
}

# check the second paremter
if [[ $2 =~ ^[0-9]+$ ]]
then
  sleep_time=$2
  echo "set period as $sleep_time seconds"
else
  sleep_time=5
  echo "default period is 5 seconds"
fi

# put all the scan results to one list.
for i in `scanDir $1`;
do
  index=$[ index+1 ]
  files[$index]=$i
  echo ${files[$index]}
done

echo =================
echo ${files[@]}
echo ================

# incase some the two files exist before our monitor begins. delete them first.
rm -f /tmp/stat.temp
rm -f /tmp/nstat.temp

while true
do
  if [ -e /tmp/stat.temp ]
  # if stat.temp exist, indicate that we collect all the change Infos of all files already and store them in stat.temp
  then
    for i in ${files[@]};
    do
      echo -ne $i >> /tmp/nstat.temp
      stat -x $i | grep Change >> /tmp/nstat.temp
    done
    diff /tmp/stat.temp /tmp/nstat.temp > /tmp/diff.temp
    if [ $? -eq 0 ]
    then
      # if the result of diff to diff.temp is 0, it shows that the two files are the same, so there is no change.
      echo "no file change"
    else
      # there are some files changed in this branch
      echo "below file(s) are changed:"
      cat /tmp/diff.temp | grep ">"
      patch /tmp/stat.temp /tmp/diff.temp
      rm /tmp/diff.temp
    fi
    rm /tmp/nstat.temp
    sleep $sleep_time
  else
    # first time, we should collect all the Infos of all files and store them.
    for i in ${files[@]};
    do
      echo collect $i
      echo -ne $i >> /tmp/stat.temp
      stat -x $i | grep Change >> /tmp/stat.temp
    done
    echo infos are collected
    sleep 2
  fi
done

缺点:

目前该方案没有考虑文件的增减带来的改变。Shell脚本里也可以实现Map,用Map的话,应该是可以实现更复杂的检测。

相关标签: Shell