1

I'm using inotify-tools (inotifywait) on CentOS 7 to execute a php script on every file creation.

When I run the following script:

#!/bin/sh
MONITORDIR="/path/to/some/dir"
inotifywait -m -r -e create --format '%w%f' "${MONITORDIR}" | while read NEWFILE
do
    php /path/to/myscript.php ${NEWFILE}
done

I can see there are 2 processes:

# ps -x | grep mybash.sh
    27723 pts/4    S+     0:00 /bin/sh /path/to/mybash.sh
    27725 pts/4    S+     0:00 /bin/sh /path/to/mybash.sh
    28031 pts/3    S+     0:00 grep --color=auto mybash.sh

Why is that, and how can I fix it?

HTMHell
  • 5,761
  • 5
  • 37
  • 79
  • As an aside -- all-caps variable names are specified by POSIX as used for variables with meaning to the shell or operating system, whereas names with at least one lower-case character are reserved for application use. See http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html – Charles Duffy May 03 '17 at 01:22

1 Answers1

0

A pipeline splits into multiple processes. Thus, you have the parent script, plus the separate subshell running the while read loop.

If you don't want that, use the process substitution syntax available in bash or ksh instead (note that the shebang below is no longer #!/bin/sh):

#!/bin/bash
monitordir=/path/to/some/dir

while read -r newfile; do
    php /path/to/myscript.php "$newfile"
done < <(inotifywait -m -r -e create --format '%w%f' "$monitordir")
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441