Skip to content

Instantly share code, notes, and snippets.

@ephemient
Created December 21, 2022 12:39
Show Gist options
  • Save ephemient/0599e22887009dd898d54471a50f255b to your computer and use it in GitHub Desktop.
Save ephemient/0599e22887009dd898d54471a50f255b to your computer and use it in GitHub Desktop.
Run a command whenever changes are detected by inotify
#!/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