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

后端 未结 5 1871
别跟我提以往
别跟我提以往 2021-02-03 14:11

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

5条回答
  •  既然无缘
    2021-02-03 15:09

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

提交回复
热议问题