Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 650
Gitnik Avatar asked May 04 '26 15:05

Gitnik


1 Answers

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
like image 89
larsks Avatar answered May 06 '26 03:05

larsks