问题描述
我有一个名为/home/user/local
的目录.每两分钟左右,就会有一个新文件转储到该目录中.我需要每2分钟检查一次此目录,以查看是否有新文件放在那里.如果有新文件,我需要将其列表放入变量中,以备后用.我该如何做这个shell脚本?
I have a directory called /home/user/local
. Every two minutes or so, a new file is dumped into this directory. I need to check this directory every 2 minutes to see if a new file/files have landed in there. And if there are new files, I need to put a list of it into a variable to use later on. How do I do this shell script?
推荐答案
#! /usr/bin/env bash
FILELIST=/tmp/filelist
MONITOR_DIR=/home/usr/local
[[ -f ${FILELIST} ]] || ls ${MONITOR_DIR} > ${FILELIST}
while : ; do
cur_files=$(ls ${MONITOR_DIR})
diff <(cat ${FILELIST}) <(echo $cur_files) || \
{ echo "Alert: ${MONITOR_DIR} changed" ;
# Overwrite file list with the new one.
echo $cur_files > ${FILELIST} ;
}
echo "Waiting for changes."
sleep $(expr 60 \* 2)
done
快速&肮脏的方式.:)它将监视目录中的更改,不仅在有新文件转储时,而且在某些文件丢失/删除时也是如此.
a quick & dirty way. :) It'll monitor the directory for changes, not only when there's new file dumped in, but also if some file is missing/deleted.
文件列表存储在变量 $ cur_files
中.
File list is stored in variable $cur_files
.
这篇关于如何在shell脚本中每2分钟查找一次目录中是否有新文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!