Last active
August 22, 2024 16:26
-
-
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.
This file contains 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/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" |
Nice!
How would you do the same, but with inotifywait running as a daemon?
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
Great script, the first usable implementation of inotifywait I've come across so far! Good work!