Friday, January 10, 2020

Watch file/folder for change and trigger an action

My use-case is that I have an upload folder which I'd like to reindex when something is uploaded/deleted. For this I watch the file size with du command.
It should be triggered via cron or systemd timer.

I run it with crond (on synology) twice a minute:

* * * * * /volume1/bin/watch.sh /volume2/shared/upload
* * * * * sleep 30; /volume1/bin/watch.sh /volume2/shared/upload

At the end of the script I run synoindex.

#!/bin/sh
##################################################
# Name:         watch.sh
# Author:       krisko
# Description:  Watch file/folder for change and trigger some action
# Date:         20200109
##################################################

usage() {
cat << EOT
Watch file/folder for change and trigger some action
NOTE: this won't work if the change size is smaller than your blocksize (typically 4k)!

USAGE: $0 (OPTION)
OPTIONS:
    -h      Show this help
    PATH    Absolute path to file/folder

EOT
exit 0
}

# call usage if needed
[[ ! -n $1 ]] || [[ $1 == "-h" ]] && usage

# file/folder to watch
WATCH=$1
# logfile to store info
LOG=/tmp/watch_${WATCH##*/}

# return current size
getsize() {
    du -s $1 | awk '{print $1}'
}

[[ -f ${LOG}.pending ]] && { echo "INFO: another instance already waiting for change, exiting..."; exit 0; }
# check if we have valid input
[[ -f $WATCH ]] || [[ -d $WATCH ]] || { echo "ERROR: invalid file specified, use -h for help."; exit 1; }
# create logfile if it does not exist
[[ ! -f $LOG ]] && getsize $WATCH > $LOG || LOGGED=$(cat $LOG)

CURRENT=$(getsize $WATCH)

[[ $LOGGED -eq $CURRENT ]] && { echo "INFO: nothing changed"; exit 0; }

# when change detected, w8 for folder stabilization and proceed
touch ${LOG}.pending
while [[ $LOGGED -ne $CURRENT ]]; do
    LOGGED=$CURRENT
    sleep 2
    CURRENT=$(getsize $WATCH)
done
rm ${LOG}.pending

# update log
echo $CURRENT > $LOG

# run your favorite command
synoindex -R $WATCH

exit 0

#################################################
# TODO/Changelog # Author # Description
#################################################
# 1.0.0 20200109 # krisko # Genesis
#################################################

1 comment: