Bash

Watch a File for Changes (no inotify dep)

admin by @admin ADMIN
Jun 15, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
inotifywait is great when available, but on systems without inotify-tools you can poll mtime. Cheap enough to use in dev/CI workflows.
Bash
Raw
# Method 1: inotifywait (Linux, package: inotify-tools)
inotifywait -e modify,close_write,move,delete /etc/myapp.conf
echo "config changed!"

# Loop until killed
while true; do
    inotifywait -e close_write /etc/myapp.conf 2>/dev/null
    systemctl reload myapp
done

# Method 2: pure-bash poll fallback
watch_file() {
    local file="$1" interval="${2:-2}"
    local last
    last="$(stat -c %Y "$file" 2>/dev/null || echo 0)"
    while sleep "$interval"; do
        local now
        now="$(stat -c %Y "$file" 2>/dev/null || echo 0)"
        if [[ "$now" -gt "$last" ]]; then
            echo "[$(date)] $file changed"
            last="$now"
        fi
    done
}

watch_file /etc/myapp.conf 5
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.