Last active
February 20, 2023 13:45
-
-
Save bdowling/6da8310b7a004345ddf1b37ff54d5db2 to your computer and use it in GitHub Desktop.
Fun little script I use to watch for file changes with inotifywait and then run commands when they are modified.
This file contains hidden or 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 | |
# quick script to make using inotifwatch easier for simple cases, | |
# such as when you are editiing files and you want to scp them to another | |
# system as soon as you make save changes. | |
# | |
# Brian Dowling | |
set -e | |
usage() { | |
echo <<EOT | |
$0 will Watch for changes and then.. | |
$0 . -- scp somefile somewhere:/tmp | |
$0 somefile -- kill -HUP someprocess | |
If you want to pass args to inotify, you can use a double --, e.g. | |
$0 . -- --someinotiy --opts -- scp somefile somewhere:/tmp | |
--eval | |
-e to use 'eval "$*"' on your command, this gives you access to the events, i.e. | |
fullpath - concatentad full path+file | |
path - dir of file change (ends in /) | |
file - filename changed | |
event - though this will only be MODIFY in this current version | |
ex (contrived): | |
watch-for-changes-then -e ~/src -- '(cd $path; ls -la "$(basename "$fullpath")"; ./build )' | |
--watch [watch] | |
This flag is optional, you can also just add the parameter without the flag | |
EOT | |
exit 1 | |
} | |
use_eval='' | |
watch='' | |
LONGOPTS="watch:,inotifyargs:,help,eval" | |
SHORTOPTS="ew:i:" | |
PARSED=$(getopt --options "$SHORTOPTS" --longoptions "$LONGOPTS" --name $0 -- "$@") | |
echo "$PARSED" | |
eval set -- "$PARSED" | |
# XXX We could potentially split args on -- and pass anything before to inotifywait ... | |
while true; do | |
# echo "a: $1" | |
case "$1" in | |
-h|--help) usage ;; | |
-e|--eval) use_eval=y; shift ;; | |
--watch) shift; watch="$1"; shift ;; | |
--) shift; break ;; | |
* ) usage ;; | |
esac | |
done | |
if [ -z "$watch" ]; then | |
[ -z "$1" ] && usage | |
watch=$1 | |
shift; | |
fi | |
if [ "${1:0:1}" == "-" ]; then | |
while [ -n "$1" -a "$1" != '--' ]; do | |
inotifyargs="$inotifyargs $1" | |
shift | |
done | |
shift | |
fi | |
[ -z "$1" ] && usage | |
# this uses -e to watch for modify then it runs the command on any event... | |
if [ -f $watch ]; then | |
recurse='' | |
else | |
recurse='-r' | |
fi | |
set +e | |
inotifywait --exclude '~$' $recurse -m -e modify -q $inotifyargs $watch | | |
while read path event file; do | |
fullpath="$path$file" | |
echo "$fullpath $event" | |
echo "$*" | |
if [ "$use_eval" = "y" ]; then | |
eval "$*" | |
else | |
"$@" | |
fi | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment