Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find if there are new files in a directory every 2 minutes in shell script?

Tags:

bash

shell

unix

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?

like image 379
user1452759 Avatar asked Nov 07 '12 06:11

user1452759


People also ask

Which command will to find all files which are changed in last 1 hour?

-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.

How do you find all files which are modified 10 minutes before?

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.

How do I monitor a directory in Linux?

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.


2 Answers

#! /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.

like image 143
procleaf Avatar answered Oct 16 '22 20:10

procleaf


inotifywait is exactly what you are looking for: http://linux.die.net/man/1/inotifywait

like image 2
sampson-chen Avatar answered Oct 16 '22 19:10

sampson-chen