Last active
August 3, 2022 12:08
-
-
Save Phlogi/e20a3f3c2be5ac631ab51817e12103df to your computer and use it in GitHub Desktop.
Polling adé
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
MONITORDIR="/tmp/test_new_files_dir/" | |
NOW_FILE="/tmp/catch_file_changes_now.touch" | |
DELAY_FILE="/tmp/catch_file_changes.touch" | |
AWAIT_TIME=20 # seconds | |
AWAIT_TIME_STR="+${AWAIT_TIME}seconds" | |
CMD="echo \"da command\"" | |
echo "[start] $(date)" | |
await_and_run () { | |
echo " [${1}] waiting ${AWAIT_TIME} + 1 seconds inside await function... (eventually running your command)" | |
sleep ${AWAIT_TIME} | |
sleep 1 # ensure it's really newer | |
touch ${NOW_FILE} | |
if [[ ${NOW_FILE} -nt ${DELAY_FILE} ]] | |
then | |
echo " [${1}] awaiting succeeded (no new files added during ${AWAIT_TIME} seconds), will run command > ${CMD} <" | |
eval "${CMD}" | |
else | |
echo " [${1}] awaing aborted, as newer file was added, will not run command yet..." | |
fi | |
} | |
# -m: Instead of exiting after receiving a single event, execute indefinitely. | |
# -r: Watch all subdirectories of any directories passed as arguments. Watches will be set up recursively to an unlimited depth. Symbolic links are not traversed. Newly created subdirectories will also be watched. | |
# -e: Event type, we use create: A file or directory was created within a watched directory. | |
inotifywait -m -r -e create --format '%w%f' "${MONITORDIR}" | while read NEWFILE | |
do | |
echo "File ${NEWFILE} has been created beneath watched folder ${MONITORDIR}" | |
touch -d"+20seconds" ${DELAY_FILE} | |
# run function in background to not block detection of newer files coming in | |
await_and_run ${NEWFILE} & | |
echo "do loop end of inotifywait, waiting for next newfile..." | |
done | |
# cleanup | |
rm -vf "${NOW_FILE}" | |
rm -vf "${DELAY_FILE}" | |
echo "[done] $(date)" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample run: