Skip to content

Instantly share code, notes, and snippets.

@hexode
Forked from wernight/inotifyexec.py
Created April 29, 2014 15:24
Show Gist options
  • Select an option

  • Save hexode/11403574 to your computer and use it in GitHub Desktop.

Select an option

Save hexode/11403574 to your computer and use it in GitHub Desktop.
#!/bin/bash -e
#
# Author: Werner Beroux <werner@beroux.com>
# Help?
if [[ $# -eq 0 || $1 == --help || $1 == -h ]]
then
echo "inotifyexec version 1.1.0"
echo "Requires inotify-tools."
echo ""
echo "Usage: inotifyexec <command> <inotifywait arguments...>"
echo "Example: inotifyexec make -r . -e modify,create,delete --exclude '*.swp'"
echo ""
echo "Once watch established, press Ctrl + C once to shutdown the watch cleanly."
if [[ $# -eq 0 ]]
then
exit 1
else
exit 0
fi
fi
exec_command=$1
shift
trigger_tmp_file=$(mktemp)
lock_tmp_file=$(mktemp)
# Listen to a single file changes, should be the temporary file changes.
inotify_single_file() {
while inotifywait -qq -e attrib $trigger_tmp_file
do
# Create the lock after all touch even have passed.
sleep 0.5
touch $lock_tmp_file
# Execute the desired command.
set +e
$exec_command
set -e
# Delete the lock
rm -rf $lock_tmp_file
done
}
# Fork a listener on the temporary file.
inotify_single_file &
rm -rf $lock_tmp_file
# Keep listening to the desired directory:
# Each change will touch the temporary file again.
inotifywait --monitor $* | while read dir ev file
do
# If there is a lock wait until it's unlocked
if [[ -e $lock_tmp_file ]]
then
inotifywait -qq -e delete $lock_tmp_file || true
# Wait until watch has been established again
sleep 0.2
fi
# Tell a change happened.
touch $trigger_tmp_file
done
rm -f $trigger_tmp_file 2> /dev/null
rm -f $lock_tmp_file 2> /dev/null
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment