Gitnik
Gitnik

Reputation: 574

inotifywait not performing the while loop in bash script

I want to put a file watcher on a directory in my Docker container. I'm using entrypoint.sh script to setup the script that places a file watcher. The setup is like so:

#!/bin/sh

# Trigger the script with the file watcher in the background
./bin/watcher.sh &

And the watcher.sh script contains the inotifywait command:

#!/bin/sh

inotifywait \
    --event create --event delete \
    --event modify --event move \
    --format "%e %w%f" \
    --monitor --outfile '/var/log/inotifywait.log' \
    --syslog --quiet --recursive \
    /etc/haproxy |
while read CHANGED;
do
    echo "$CHANGED"
    haproxy -W -db -f /etc/haproxy/haproxy.cfg -p /var/run/haproxy.pid -sf $(cat /var/run/haproxy.pid) &
done

However, although the watcher is listed when i check with top, and it reports changes in the defined log file, the loop never triggers. I've tried debugging the loop with simple:

    touch /var/log/special.log
    echo "${CHANGED}" >> /var/log/special.log

But file never gets created, and nothing gets echoed in it. What is the right way to use inotifywait with loop in bash script?

Upvotes: 3

Views: 2984

Answers (1)

larsks
larsks

Reputation: 312730

You are explicitly sending output to a file rather than stdout using the --outfile option. Nothing is ever written to stdout, so the read statement in your while loop never reads any data.

You probably want:

inotifywait \
    --event create --event delete \
    --event modify --event move \
    --format "%e %w%f" \
    --monitor \
    --syslog --quiet --recursive \
    /etc/haproxy |
while read CHANGED;
do
    echo "$CHANGED"
    haproxy -W -db -f /etc/haproxy/haproxy.cfg -p /var/run/haproxy.pid -sf $(cat /var/run/haproxy.pid) &
done

Upvotes: 4

Related Questions