DEV Community

John Robertson
John Robertson

Posted on • Updated on

Event Driven Bash

Alt Text
Bash is very useful when it comes to automating system administration tasks. Sometimes you need to take action based on external events, and there aren't a lot of examples of how this can be done. It's pretty straightforward:

#!/bin/bash -eu

# Launch inotifywait monitoring the syslog in a subprocess.
# Redirect stdout of subshell to pipe #3
exec 3< <(exec inotifywait -m /var/log/syslog)

# Read each line of output from inotifywait
while read -u 3 FILE OPS; do

   # stdin, stdout, stderr all available in loop

   echo "FILE= '$FILE', OPS= '$OPS'"

   # OPS are comma separated. Swap comma for space, deal with each individually.
   for op in ${OPS//,/ }; do

      # Branch on $op
      case $op in

         MODIFY)
            echo "$FILE was modified.";;

         ACCESS)
            echo "$FILE was accessed.";;

         CLOSE_NOWRITE)
            echo "$FILE was closed without changes."
            break 2;; 

# Other actions go here
      esac
   done
done

# Close pipe
exec 3<&-

# Only get here on loop exit, or if inotifywait quits.
exit 0

To exercise the script, try running it and then pulling up your syslog in a pager. When you exit the pager, your script should exit as well.
This and other examples are available on Github.
I'll be happy to try and answer any questions.

Top comments (0)