Skip to content

Instantly share code, notes, and snippets.

@yfe404
Last active November 1, 2017 10:01
Show Gist options
  • Save yfe404/592291b15e60cb44fdb5c6a301c5fe2e to your computer and use it in GitHub Desktop.
Save yfe404/592291b15e60cb44fdb5c6a301c5fe2e to your computer and use it in GitHub Desktop.
Simple directory watcher - allows you to monitor recursively a directory for changes in a file. Each time a changed is made, executes the comman that you specified
#/bin/bash
##################################################################
# SIMPLE DIRECTORY WATCHER
#
# Usage:
# bash test.sh
#
# Role:
# Simple Directory Watcher allows you to monitor
# recursively a directory for changes in a file
# each time a changed is made, execute a command
# that you specified.
#
# Parameters: (currently variables, someday arguments)
# - DIR_MONIT: The directory you want to monitor for changes.
# - COMMAND: The command to execute each time a change occurs.
# - TEMPO_IN_SECONDS: the time to wait in seconds between each scan
# for changes.
#
# Version:
# 0.1
# Author:
# Yann Feunteun
# <[email protected]>
#
##################################################################
DIR_MONIT="/home/joe/some_java_project"
COMMAND="mvn package"
TEMPO_IN_SECONDS=2
# Beacuse I don't find a way to either use two shell
# within Emacs or use a Ctrl-c like to stop the process
# so to quit the program I use kill $(cat $PWD/pid.txt)
echo $$ > pid.txt
cd $DIR_MONIT && $COMMAND
# record last execution time to compare it to last changed time
# in DIR_MONIT
last_execution_time=$(date +%s)
while true
do
# Get the timestamp of the oldest file in the directory and
# subdirectories of DIR_MONIT
last_modified_time=$(find $DIR_MONIT 2> /dev/null | xargs stat -c%Z | sort -n | tail -n 1)
# Uncomment the following line to debug
#echo "Last modified time is $last_modified_time, last time command was executed is $last_execution_time"
sleep $TEMPO_IN_SECONDS
if [ $last_execution_time -lt $last_modified_time ]; then
# Uncomment the following line to debug
#echo "Command should be executed since file(s) has changed since last execution"
cd $DIR_MONIT && $COMMAND
last_execution_time=$(date +%s)
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment