Using inotify in a script to monitor a directory

10,779

Solution 1

It turns out all I had to do was pipe the command into a while loop:

!/bin/sh

inotifywait -mqr -e close_write "/root/secondfolder/" | while read line
do
echo "close_write"
done

Solution 2

You are not far away from solution. If you want to use inotifywait in your while statement you should not use -m option. With this option inotifywait never end because it's the monitor option. So you never go into the while.

This should work :

#!/bin/sh

while inotifywait -r -e close_write "/root/secondfolder/"
do
    echo "close_write"
done
Share:
10,779
mib1413456
Author by

mib1413456

Updated on June 14, 2022

Comments

  • mib1413456
    mib1413456 almost 2 years

    I have written a bash script to monitor a particular directory "/root/secondfolder/" the script is as follows:

    #!/bin/sh
    
    while inotifywait -mr -e close_write "/root/secondfolder/"
    do
        echo "close_write"
    done
    

    When I create a file called "fourth.txt" in "/root/secondfolder/" and write stuff to it, save and close it, it outputs the following but it does not echo "close_write":

    /root/secondfolder/ CLOSE_WRITE,CLOSE fourth.txt
    

    can someone point me in the right direction?

  • mib1413456
    mib1413456 almost 10 years
    Thank you for your response but I found another solution that allows me to monitor the directory indefinitely and get the output.
  • F. Hauri  - Give Up GitHub
    F. Hauri - Give Up GitHub almost 8 years
    ... And you could invert the fork see my answer there.
  • Phob
    Phob over 3 years
    This is suboptimal because there may be multiple close_writes before the next inotifywait process starts. It's better to use inotifywait's --monitor mode if you care about processing every single message.