1

On my Debian Buster system I want to run a bash script when a certain file is modified. I have created and enabled a service in /etc/systemd/system which looks like this

[Service]
ExecStart=/usr/local/bin/watch_file.sh
Restart=always
RestartSec=1
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=backup-channels
User=root
Group=root

[Install]
WantedBy=multi-user.target

and the file watch_file.sh looks like this

#!/bin/bash
while inotifywait -e close_write "path_to_watched_file"
do
    sh /usr/local/bin/action_to_perform.sh
done

All files are owned by the root user. Things are ok as long as the root user modifies the file. However, I would like to run the script as well when a non-root user modifies the file. Currently, a modification by a user different from root does not trigger the script action_to_perform.sh.

3
  • 1
    using inotifywait in a loop instead of monitor mode (-m) is prone to race conditions that can miss events.
    – A.B
    Mar 14, 2021 at 18:18
  • @A.B Thanks! What would be a better solution then? I wan't the monitoring to be "permanent", that is, the monitoring process should not exit when a file modification has been noted.
    – 220284
    Mar 14, 2021 at 21:19
  • check how you can use the -m option instead
    – A.B
    Mar 14, 2021 at 23:42

1 Answer 1

2

inotifywait doesn't care about effective UIDs/GIDs - it works on a different level.

The while loop you have here will terminate whenever inotifywait exits with a non-zero return status - perhaps that's your issue:

EXIT STATUS

1 An error occurred in execution of the program, or an event occurred which was not being listened for. The latter generally occurs if something happens which forcibly removes the inotify watch, such as a watched file being deleted or the filesystem containing a watched file being unmounted.

Please try changing it to

#! /bin/bash
while inotifywait -e close_write "path_to_watched_file"; true; do
    sh /usr/local/bin/action_to_perform.sh
done

It will burn CPU cycles if the file is not present, you can add sleep 1 after the action_to_perform.

1
  • Works indeed, many thanks!
    – 220284
    Mar 14, 2021 at 17:32

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .