【问题标题】:Watch a file for change监视文件以进行更改
【发布时间】:2010-11-19 10:37:04
【问题描述】:

我想查看文件 xyz.txt 的任何更改,并在有更改时通过电子邮件将整个文件发送给我。是否有一个 Liner(或几行 shell 脚本)?

更新:

# Check if my.cnf has been changed in the last 24 hours
# if yes, as in the following case, simply send the file
# if it has not been changed in the last 24 hours, do nothing.

# find /etc/ -name my.cnf -mtime 0
/etc/my.cnf

# cat /etc/my.cnf | mail shantanu@company.com

现在,如果有人可以展示如何在 shell 脚本或 1 个命令中绑定这两行。

【问题讨论】:

  • 你可以使用fswatch,它是跨平台且直接的fswatch -o my_file | xargs -n1 -I{} my_program

标签: linux shell command-line


【解决方案1】:

您可以使用inotifywait。它等待对文件的更改,然后执行命令(例如,在您的情况下类似于 msmtp)。

【讨论】:

    【解决方案2】:

    您应该查看inotify,它可以监视文件或目录并报告更改。

    【讨论】:

      【解决方案3】:

      正如我从 another question over at superuser 那里了解到的(所有功劳归于那里):

      entr (http://entrproject.org/) 提供更友好的 inotify 界面(并且还支持 *BSD 和 Mac OS X)。

      这会监视给定文件(或多个文件)的更改,并在它更改时(瞬间)运行命令。所以你可以这样做:

      echo /etc/my.cnf | \
        entr sh -c 'cat /etc/my.cnf | mail -E -s "file changed" shantanu@company.com'
      

      (PS。感谢Denis对邮件命令的回答)

      【讨论】:

        【解决方案4】:

        inotify-hookable 是一个非常容易用于此目的的 perl 脚本。例如,

        inotify-hookable -f /path/to/file -c "latexmk -pdf /path/to/file" &
        inotify-hookable -f /path/to/file -c "cp /path/to/file /path/to/copy" &
        

        -f 用于查看的文件 -c 运行命令

        我也让它在远程计算机上观看文件,但是当观看的文件在更新之前被删除时,inotify-hookable 完成了。

        我是从 Debian 安装的。 CPAN 链接:https://metacpan.org/pod/App::Inotify::Hookable

        【讨论】:

          【解决方案5】:

          试试这个:

          find /etc/ -name my.cnf -mtime 0 -exec sh -c 'cat {} | mail -E -s "file changed" shantanu@company.com' \;
          

          mail-E 选项可防止其发送正文为空的消息(如果find 不返回任何内容而cat 不输出任何内容,就会出现这种情况。

          【讨论】:

          【解决方案6】:
          #!/bin/ksh
          
          ls -lt /usr/tip30/prtfile/asb270.prt|awk '{print $6$7$8}'|awk -F: '{print $1$2}'
           > /tmp/lastupdated.temp
          read input_pid < /tmp/lastupdated.temp
          echo "$input_pid"
          
          while [ "$input_pid" -eq "`ls -lt /usr/tip30/prtfile/asb270.prt | awk '{print $6
          $7$8}'|awk -F: '{print $1$2}'`" ]; do
             echo "file has not changed "
             sleep 30
          done
          echo "file changed `ls -lt /tmp/lastupdated.temp`"
          rm /tmp/lastupdated.temp
          

          【讨论】:

          • 请格式化您的代码/提供一些解释为什么这可以解决手头的问题。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-04-04
          • 1970-01-01
          • 2012-09-02
          • 1970-01-01
          • 2011-06-18
          相关资源
          最近更新 更多