1

我最初想要一个脚本,当我在我的电脑中插入一个 USB 记忆棒时运行一个脚本,然后当它被移除时运行另一个脚本,我搞砸了 udev 没有任何成功,所以这显然不是最好的选择,然后我遇到了inotifywait 我可以在我的驱动器安装时查看一个文件夹,因为这会给我我正在寻找的 CREATE,ISDIR myfolder 输出,但是使用它来实际触发外部脚本有点超出我的编程技能,我看过 EXPECT 但看不到我将如何完成我的任务,我想基本上我需要创建一个遵循下面显示的流程的期望脚本

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

可能有一种更简单的方法可以做到这一点,但我到处搜索并尝试了各种不同的组合,简而言之,我希望在创建某个文件夹时运行一个脚本,然后在删除它时运行另一个脚本,是否有这样做的简单方法?

4

1 回答 1

0

您只需要生成该过程并等待所需的单词。就这样。

#!/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

输出 :

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

在生成时inotifywait,我添加了更多选项。该-m标志用于持续监控,因为默认情况下inotifywait将在第一个事件时退出,并且-r意味着递归或检查子目录。

我们需要指定-e标志以及我们想要通知的事件列表。所以,在这里,我们要监控文件夹的createdelete事件。

参考:inotifywait

于 2016-02-15T07:03:09.873 回答