【问题标题】:Using expect and inotifywait to watch for changes in a folder on linux使用 expect 和 inotifywait 观察 Linux 上文件夹的变化
【发布时间】:2016-02-12 15:55:27
【问题描述】:

我最初想在我的 PC 中插入 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

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

【问题讨论】:

    标签: linux expect udev inotifywait


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-01
      • 1970-01-01
      • 2020-03-21
      • 2012-09-30
      相关资源
      最近更新 更多