Using expect and inotifywait to watch for changes in a folder on linux

793 views Asked by At

I originally wanted to have a script that ran when I inserted a USB stick in my PC and then another script when it was removed, I messed around with udev with no success whatsoever so this obviously wasn't the best option, I then came across inotifywait which I could get to watch a folder for when my drive was mounted, as this would give me the CREATE,ISDIR myfolder output I was looking for, however using this to actually trigger an external script is a bit beyond my programming skills, I have looked at EXPECT but cant see how I'd achieve my task, I guess basically I need to create an expect script that follows the flow shown below

Expect spawns the inotifywait process
expect then starts a loop
if the loop sees "CREATE,ISDIR test" then run script active.sh
if the loop sees "DELETE,ISDIR test" then run scrip inactive.sh
Loop

There may be a simpler way to to do this but I have scoured everywhere and tried all sorts of different combinations, in a nutshell I want a script to run when a certain folder is created then another to run when it is deleted, is there a simple way of doing this?

1

There are 1 answers

0
Dinesh On

You just have to spawn the process and wait for the required word. That's all.

#!/usr/bin/expect
# Monitoring '/tmp/' directory
set watchRootDir "/tmp/"
# And, monitoring of folder named 'demo'
set watchFolder "demo"

puts "Monitoring root directory : '$watchRootDir'"
puts "Monitoring for folder : '$watchFolder'"

spawn  inotifywait -m -r -e create,delete /tmp
expect {
        timeout {puts "I'm waiting ...";exp_continue}
        "/tmp/ CREATE,ISDIR $watchFolder" {
            puts "Folder created"
            #  run active.sh here ...
            exp_continue
         }
        "/tmp/ DELETE,ISDIR $watchFolder" {
            puts "Folder deleted"
            #  run inactive.sh here ...
         }
}
# Sending 'Ctrl+C' to the program, so that it can quit 
# gracefully. 
send "\003"
expect eof

Output :

dinesh@myPc:~/stackoverflow$ ./Jason 
Monitoring root directory : '/tmp/'
Monitoring for folder : 'demo'
spawn inotifywait -m -r -e create,delete /tmp
Setting up watches.  Beware: since -r was given, this may take a while!
Watches established.
I'm waiting ...
I'm waiting ...
/tmp/ CREATE,ISDIR demo
Folder created
I'm waiting ...
/tmp/ DELETE,ISDIR demo
Folder deleted

While spawning inotifywait, I have added few more options. The -m flag is for continuous monitoring as by default inotifywait will exit on the first event and -r means recursively or check through sub-directories as well.

we will need to specify the -e flag along with the list of events we want to be notified about. So, here, we want to monitor the create and delete events of folder.

Reference : inotifywait