Created
December 21, 2022 12:39
-
-
Save ephemient/0599e22887009dd898d54471a50f255b to your computer and use it in GitHub Desktop.
Run a command whenever changes are detected by inotify
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 | |
set -euo pipefail | |
declare -a ARGS=() INOTIFY_ARGS | |
while (($#)); do | |
case $1 in | |
--) break;; | |
*) ARGS+=("$1");; | |
esac | |
shift | |
done | |
if [[ ${1:-} = -- ]]; then | |
shift | |
INOTIFY_ARGS=("${ARGS[@]}") ARGS=("$@") | |
else | |
INOTIFY_ARGS=(-r .) | |
fi | |
if ! ((${#ARGS[*]})); then | |
echo "usage: $(basename "$0") [inotifywait args] [--] <command> [args]" | |
exit | |
fi | |
run() { | |
if command "${ARGS[@]}"; then | |
echo ok. | |
else | |
echo "fail. $?" | |
fi | |
} | |
exec {fd}< <( | |
command inotifywait -e modify -e attrib -e move -e create -e delete -m "${INOTIFY_ARGS[@]}" | |
); pid=$! | |
trap "kill $pid" EXIT | |
trap exit SIGINT SIGQUIT SIGTERM | |
run $fd<&- | |
while read -r -u $fd; do | |
printf ':: %s\n' "$REPLY" >&2 | |
while read -r -t 1 -u $fd; do | |
printf ':: %s\n' "$REPLY" >&2 | |
done | |
run $fd<&- | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment