1

我正在尝试运行计划的 cron 作业并将输出通过电子邮件发送给几个用户。但是,我只想在发生新情况时给用户发送电子邮件。

本质上,这就是发生的事情:

我运行一个 python 脚本,然后它检查 FTP 服务器上的文件名。如果文件名不同,则下载文件并开始解析信息。先前下载的文件的文件名存储在 last.txt 中 - 如果确实找到了一个新文件,那么它只会更新 last.txt 中的文件名

如果文件名相同,则停止处理并仅输出相同的文件。

本质上,我的想法是我可以做类似的事情:

cp last.txt temp.last.txt | python script.py --verbose > report.txt | diff last.txt temp.last.txt

不过,这就是我卡住的地方。本质上,我想区分这两个文件,如果它们相同 - 什么也不会发生。但是,如果它们不同,我可以通过 mail 命令将 report.txt 的内容通过电子邮件发送到几个电子邮件地址。

希望我足够详细,在此先感谢!

4

1 回答 1

2

首先,代码中不需要管道|,您应该分别发出每个命令。要么用分号分隔它们,要么将它们写在脚本的不同行上。

对于问题本身,一种解决方案是将 diff 的输出重定向到报告文件,例如:

cp last.txt temp.last.txt 
python script.py --verbose > report.txt
diff last.txt temp.last.txt > diffreport.txt

然后,您可以按照此处所述检查报告文件是否为空:http ://www.cyberciti.biz/faq/linux-unix-script-check-if-file-empty-or-not/

根据结果​​,您可以发送 diffreport.txt 和 report.txt 或将其全部删除。

这是一个简单的示例,说明您的 cron 作业脚本的外观:

#!/bin/bash

# Run the python script
cp last.txt temp.last.txt
python script.py --verbose > report.txt
diff last.txt temp.last.txt > diffreport.txt

# Check if file is empty or not
if [ -s "diffreport.txt" ]
then
    # file is not empty, send a mail with the attachment
    # May be call another script that will take care of this task.
else
    # file is empty, clean up everything
    rm diffreport.txt report.txt temp.last.txt
fi
于 2013-07-28T20:12:57.820 回答