观看文件以进行更改

时间:2010-11-19 10:37:05

标签: linux shell command-line

我想观看文件xyz.txt的任何更改,并在发生更改时通过电子邮件发送给我整个文件。是否有一个衬里(或几行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个命令中绑定这两行。

6 个答案:

答案 0 :(得分:21)

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

答案 1 :(得分:8)

您应该查看可以查看文件或目录并报告更改的inotify

答案 2 :(得分:4)

尝试一下:

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

-E的{​​{1}}选项会阻止它发送包含空主体的消息(如果mail没有返回任何内容而find输出任何内容,则会出现这种情况。

答案 3 :(得分:2)

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

答案 4 :(得分:1)

我从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对邮件命令的回答)

答案 5 :(得分:-2)

#!/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
相关问题