Skip to content

Instantly share code, notes, and snippets.

@mpapi
Last active March 14, 2023 12:46
Show Gist options
  • Save mpapi/4656389 to your computer and use it in GitHub Desktop.
Save mpapi/4656389 to your computer and use it in GitHub Desktop.
A simple shell script that uses inotify in Linux to run shell commands whenever files matching a pattern are changed.
#!/bin/sh
#
# Usage: whenever.sh [pattern] [command]
#
# Executes a command whenever files matching the pattern are closed in write
# mode. "{}" in the command is replaced with the matching filename (via xargs).
# Requires inotifywait from inotify-tools.
#
# For example,
#
# whenever.sh '\.md$' 'markdown -f $(basename {} .md).html {}'
#
# This runs "markdown -f my-document.html my-document.md" whenever
# my-document.md is saved.
#
set -e -u
PATTERN="$1"
COMMAND="$2"
inotifywait -q --format '%f' -m -r -e close_write . \
| grep --line-buffered $PATTERN \
| xargs -I{} -r sh -c "echo [\$(date -Is)] $COMMAND && $COMMAND"
@superjamie
Copy link

Very useful, thanks for this!

@fabswt
How would you do the same, but with inotifywait running as a daemon?

I start it as a background process with my desktop session (as I'm using it to notify-send).

If you want it system-wide without output, you could write a systemd unit to run the inotifywait command directly. Look up the correct syntax for writing a service unit for a process which never exits.

Skimming https://www.digitalocean.com/community/tutorials/understanding-systemd-units-and-unit-files you probably want a simple type service with the inotifywait command as ExecStart.

Good luck!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment