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?
-mtime n is an expression that finds the files and directories that have been modified exactly n days ago. In addition, the expression can be used in two other ways: -mtime +n = finds the files and directories modified more than n days ago. -mtime -n = finds the files and directories modified less than n days ago.
Syntax of find command with “-mmin n” option -n : find command will look for files modified in last n minutes. +n : find command will look for files modified in before the last n minutes i.e. which are not modified in last n mins. n : find command will look for files which are modified exactly n minutes ago.
In Linux, we can use the inotify interface to monitor a directory or a file. We do this by adding a watch to the directory or file. When we add a watch to a file, we can monitor it. For example, we'll know when a process opens, modifies, reads closes, moves, or deletes the file.
#! /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.
File list is stored in variable $cur_files
.
inotifywait
is exactly what you are looking for: http://linux.die.net/man/1/inotifywait
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With