Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@XertroV
Last active September 5, 2019 01:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save XertroV/4a1085ecd7abc97a1f9cfae68dd10659 to your computer and use it in GitHub Desktop.
Save XertroV/4a1085ecd7abc97a1f9cfae68dd10659 to your computer and use it in GitHub Desktop.
Watch.sh - a generic watch-for-files-and-restart-a-command utility for linux.
#!/usr/bin/env bash
# if you have issues, try increasing /proc/sys/fs/inotify/max_user_watches
usage(){
echo "$0 -i 'INCLUDE_FILES' [-e 'EXCLUDE_FILES'] -c 'COMMAND'"
cat << EOF
watch.sh - a generic watch-for-files-and-restart-a-command utility for linux.
Author: Max Kaye
License: Public Domain
EOF
echo " Included files should be a 'find' pattern; e.g. '*.js'"
echo " Excluded files should be regex (processed using grep); e.g. 'node_modules/.*'"
echo ""
echo " Example: ./watch.sh -i '*.js' -e 'node_modules/.*' -c 'npm run app'"
echo ""
exit 1
}
while [ $# -gt 0 ]; do
case $1 in
-c) command="$2"; shift 2 ;;
-i) include="$2"; shift 2 ;;
-e) exclude="$2"; shift 2 ;;
-*) echo -e "$0: Unrecognized option: $1" >&2; usage ;;
*) echo -e "$0: Unexpected argument: $1" >&2; usage ;;
esac
done
if [[ "$command" == "" ]] || [[ "$include" == "" ]]; then
echo -e "$0: Must include both -c and -i to specify command to run and included files to watch\n" >&2
usage
fi
kill_my_jobs() {
#echo "jobs to kill: $(jobs -p)"
PID="-${1:-$(jobs -p)}"
kill -SIGINT $PID || echo "Unable to kill process: $PID" >&2
}
sigint_handler() {
kill_my_jobs
echo ""
exit
}
trap sigint_handler SIGINT
while true; do
files_to_watch=$(find . -iname "$include" | grep -i -v "$exclude")
nlines=$(echo "$files_to_watch" | wc -l)
echo "Watching $nlines files"
echo "$0: running command '$command'"
setsid $command &
PID="$!"
echo "PID: $PID"
inotifywait -e modify -e move -e create -e delete -e attrib $files_to_watch
kill_my_jobs $PID
#sleep 1
wait
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment