-->

inotify script runs twice?

2019-09-12 05:39发布

问题:

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?

回答1:

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")