Bash shell 脚本在没有 Inotify 的情况下在新文件出现时获取电子邮件

问题描述 投票:0回答:3

有什么理由要创建 Bash shell 脚本来将所有新传入的文件信息(文件名;到达日期/时间;文件大小)发送到某个文件夹中。

我无法使用inotify,所以请不要将其视为选项。

bash shell sh
3个回答
6
投票

类似:

#!/bin/bash

monitor_dir=/path/to/dir
[email protected]

files=$(find "$monitor_dir" -maxdepth 1 | sort)
IFS=$'\n'

while true
do
  sleep 5s

  newfiles=$(find "$monitor_dir" -maxdepth 1 | sort)
  added=$(comm -13 <(echo "$files") <(echo "$newfiles"))

  [ "$added" != "" ] &&
    find $added -maxdepth 1 -printf '%Tc\t%s\t%p\n' |
    mail -s "incoming" "$email"

  files="$newfiles"
done

只要没有创建名称中包含换行符的文件,这应该可以正常工作。其他警告是,我看不到

find
的任何选项来输出人类可读的大小,因此获得它需要进一步处理。此外,大多数文件系统实际上并不存储文件创建时间,而是使用修改时间(在这种情况下它不会产生任何真正的区别)。

更新

要测试脚本并将其打印到终端,只需删除

mail
行和上一行末尾的管道 (
|
)。我将监控目录改为顶部的变量而不是直接编码,所以在这里填写目录。然后将脚本放入文件中,设置可执行权限并运行(在脚本目录中时为
./filename
)。如果您将文件放入目录中,几秒钟后它们应该会出现在脚本的控制台上。

要发送电子邮件,您需要确保您的系统设置为从命令行发送电子邮件。您的发行版应该有相关说明。您可以发送测试电子邮件:

<<<hello mail -s "test email" [email protected]

如果您不想设置发送电子邮件,也可以通过

username@localhost
向本地系统用户发送电子邮件。您可以使用
mail
命令进行检查,或者可以设置不同的邮件阅读器,例如 Thunderbird。


0
投票

检查新文件的另一种方法是使用 bash 内置函数,该方法不使用

ls
find
,并且也适用于收件箱格式文件(其中所有消息按顺序存储在单个文件中)。

更优雅的解决方案仅在您的收件箱不受其他方式监控的情况下才有效(即邮件进入,写入文件,并且没有人读取它):

#!/bin/bash

inbox_dir=/path/to/dir

while true; do
    for f in "$inbox_dir"/*; do
        [ -N "$f" ] && {
            head -1 "$f" >/dev/null
            echo "unread stuff in file: $f"
        }
    done
    sleep 5
done

另一种解决方案在访问(读取)邮件文件时也有效,它使用时间戳:

#!/bin/bash

stamp=/tmp/email_monitor.stamp
inbox_dir=/path/to/dir

touch "$stamp"
while true; do
    mv "$stamp" "$stamp.old"
    touch "$stamp"
    for f in "$inbox_dir"/*; do
        [ "$f" -nt "$stamp.old" -a "$f" -ot "$stamp" ] && {
            echo "new stuff in file: $f"
        }
    done
    rm -f "$stamp.old"
    sleep 5
done

0
投票

我正在为类似的问题而苦苦挣扎。

我需要一个每天只运行一次的脚本(通过 cron)

这是代码:

#!/bin/bash

[email protected]
files=/path/to/file

if test -d "/path/to/file"
then

  find $files -newermt '1 day ago' -printf '%Tc\t%s\t%p\n' |
  mail -s "Subject" "$email"

else

  echo "The file doesn't exist..." | mail -s "Subject" "$email"

fi
exit
© www.soinside.com 2019 - 2024. All rights reserved.