Skip to content

Instantly share code, notes, and snippets.

@ruliana
Forked from mpapi/whenever.sh
Created January 19, 2017 11:52
Show Gist options
  • Save ruliana/db8c98832a4864f952db1c058c31dfeb to your computer and use it in GitHub Desktop.
Save ruliana/db8c98832a4864f952db1c058c31dfeb 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"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment