Search code examples
linuxbashprocessinotify

Use inotifywait -m in script without creating extra process?


I am not sure this is possible, but I've often thought that and some solutions have amazed me. Is it possible to create the equivalent of the following script without creating two processes (in this case, it is clear two processes are created because there is a pipe):

#!/bin/bash

EVENTS="CREATE,CLOSE_WRITE,DELETE,MODIFY,MOVED_FROM,MOVED_TO"
inotifywait -e "$EVENTS" -m -r ~/Desktop/testing | \
  while true; do
    read TMP
    echo "${TMP}" >> ~/Desktop/eventlog
  done

Note that inside the while loop I do want to have access to the event.

It seems to me that a pipe is necessary because we need to write with one process and read from another. But maybe there exists a trick?


Solution

  • In bash 4.2, you can set the lastpipe option to allow the while loop to run in the current shell instead of a separate process.

    shopt -s lastpipe
    inotifywait -e "$EVENTS" -m -r ~/Desktop/testing |
      while true; do
        read TMP
        echo "${TMP}" >> ~/Desktop/eventlog
      done
    

    (You don't need an explicit line continuation after the |, since bash knows that a line cannot end with that character.)