Skip to content

Instantly share code, notes, and snippets.

@mpapi
Last active August 22, 2024 16:26
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"
@adacaccia
Copy link

Great script, the first usable implementation of inotifywait I've come across so far! Good work!

@ernoaapa
Copy link

Nice!

@fabswt
Copy link

fabswt commented Aug 24, 2020

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

@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