Search code examples
bashinotifywait

Triggering Event in BASH with inotifywait


I'm monitoring a log file (it's a PBX queue file, it's written to when a call comes in and it's the result of what happens to the call, whether the caller hangs up, etc)

Here's what I have:

while inotifywait -m -e close_write /var/log/asterisk/queue_log_test;
do
  if [ tail -n1 /var/log/asterisk/queue_log | grep EXITWITHTIMEOUT ];
    then
            php /usr/local/scripts/queue_monitor/pbx_queue_timeout.php
  elif [ tail -n1 /var/log/asterisk/queue_log | grep ABANDON ];
    then
            php /usr/local/scripts/queue_monitor/pbx_queue_abandon.php
  elif [ tail -n1 /var/log/asterisk/queue_log | grep COMPLETE ];
    then
            php /usr/local/scripts/queue_monitor/pbx_queue_complete.php
  else
    # Don't do anything unless we've found one of those
    :
  fi
done

Now, if I run the script, it successfully sets up the watches and detects the change/close (I've tried both MODIFY and CLOSE_WRITE, both work)

Setting up watches.
Watches established.
/var/log/asterisk/queue_log_test CLOSE_WRITE,CLOSE

But the event is never triggered (I have tested the PHP scripts outside of the inotify script and they execute splendidly)

If I run a tail by hand of the file that's being watched, it's successful and finds the phrase:

[root@pbx ...local/scripts/queue_monitor]: tail /var/log/asterisk/queue_log_test
ABANDON
[Load: 0.00] [Time: 19:04:43]
[root@pbx ...local/scripts/queue_monitor]:

What is it I'm missing here?


Solution

  • You are using the -m switch of inotifywait, which makes it run indefinitely:

       -m, --monitor
              Instead of exiting  after  receiving  a  single  event,  execute
              indefinitely.   The default behaviour is to exit after the first
              event occurs.
    

    And the while loop is waiting for it to finish, so it can evaluate is exit code to decide if the loop should continue or not.