Last active
July 14, 2023 07:54
-
-
Save senko/1154509 to your computer and use it in GitHub Desktop.
OnChange - Watch current directory and execute a command if anything in it changes
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
#!/bin/bash | |
# | |
# Watch current directory (recursively) for file changes, and execute | |
# a command when a file or directory is created, modified or deleted. | |
# | |
# Written by: Senko Rasic <[email protected]> | |
# | |
# Requires Linux, bash and inotifywait (from inotify-tools package). | |
# | |
# To avoid executing the command multiple times when a sequence of | |
# events happen, the script waits one second after the change - if | |
# more changes happen, the timeout is extended by a second again. | |
# | |
# Installation: | |
# chmod a+rx onchange.sh | |
# sudo cp onchange.sh /usr/local/bin | |
# | |
# Example use - rsync local changes to the remote server: | |
# | |
# onchange.sh rsync -avt . host:/remote/dir | |
# | |
# Released to Public Domain. Use it as you like. | |
# | |
EVENTS="CREATE,CLOSE_WRITE,DELETE,MODIFY,MOVED_FROM,MOVED_TO" | |
if [ -z "$1" ]; then | |
echo "Usage: $0 cmd ..." | |
exit -1; | |
fi | |
inotifywait -e "$EVENTS" -m -r --format '%:e %f' . | ( | |
WAITING=""; | |
while true; do | |
LINE=""; | |
read -t 1 LINE; | |
if test -z "$LINE"; then | |
if test ! -z "$WAITING"; then | |
echo "CHANGE"; | |
WAITING=""; | |
fi; | |
else | |
WAITING=1; | |
fi; | |
done) | ( | |
while true; do | |
read TMP; | |
echo $@ | |
$@ | |
done | |
) |
Thanks for the script! I'm having trouble figuring out where the 1 second is defined, as I'd like to extend it.
@tdmalone, read -t 1 LINE
tries to read one line, but with a one second timeout. read
is a bash
builtin, and is documented on the bash
man page.
Thanks! I modified this script, now it can use entered path, not current directory only =)
Changes there : https://gist.github.com/AVAtarMod/e8bb8ee64cdb009f68d2f70615632b62
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Cool idea, but how would you pass extra arguments with quotes? say i want
onchange.sh rsync -a --exclude='folder with space' host:/path
?