bash cron:将输出发送到文件,然后通过电子邮件发送文件给我

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5455684/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 23:41:43  来源:igfitidea点击:

cron: sending output to file then EMAILing file to me

emailbashubuntucron

提问by oompahloompah

I am writing a series of cron jobs. I want each task to log its output to file, and then I want the contents of the file mailed to me at say [email protected]

我正在编写一系列 cron 作业。我希望每个任务都将其输出记录到文件中,然后我希望将文件的内容邮寄给我说 [email protected]

I think logging the output to file can be done using simple pipe redirection like this:

我认为可以使用像这样的简单管道重定向来将输出记录到文件中:

30 0 * * * /path/to/script1 > task1.log
30 1 * * * /path/to/script2 > task2.log

However, I am not sure how to mail the files (or simply their contents) to me in seperate emails to [email protected]

但是,我不确定如何通过单独的电子邮件将文件(或只是它们的内容)邮寄给 [email protected]

Also, is there a way to dynamically create the log file names, based on the date, so that the log names would be something like %Y%m%d.task1.log ?

另外,有没有办法根据日期动态创建日志文件名,以便日志名称类似于 %Y%m%d.task1.log ?

Where the prefix is the date ?

前缀是日期在哪里?

I am running on Ubuntu 10.0.4 LTS

我在 Ubuntu 10.0.4 LTS 上运行

回答by sarnold

If your system has a working /usr/bin/sendmail(doesn't have to be sendmailsendmail, most mail servers provide a /usr/bin/sendmailwrapper script) then you can use the mail(1)utility to send mail:

如果您的系统有一个工作/usr/bin/sendmail(不必是sendmailsendmail,大多数邮件服务器提供/usr/bin/sendmail包装脚本),那么您可以使用该mail(1)实用程序发送邮件:

echo "hello world" | mail -s hello [email protected]

mail(1)is pretty primitive; there's no MIME file attachments, you're stuck with plaintext.

mail(1)很原始;没有 MIME 文件附件,您只能使用纯文本。

If mutt(1)is installed, you can use MIME to attach files:

如果mutt(1)已安装,则可以使用 MIME 附加文件:

echo "hello world" | mutt -a task*.log -- [email protected]

As for giving the logfiles dates:

至于给日志文件日期:

$ echo "hi" > $(date "+%Y%m%dlog.txt")
$ cat 20110328log.txt              
hi
$

So, try this:

所以,试试这个:

30 1 * * * /path/to/script2 > $(date "+\%Y\%m\%dlog.txt") && mutt -a $(date "+\%Y\%m\%dlog.txt") -- [email protected]