Date in Crontab email subject

喜你入骨 提交于 2021-01-07 01:34:03

问题


I have an ubuntu server where I schedule crontab processes like the following.

59 2 * * * : Backup Settings; ~/backup_settings.sh

At the conclusion of the process, I will get an email with the subject line "Backup Settings ...". Essentially the noop function (:) does nothing with the words "Backup Settings". I would like to add today's date to the email subject. Naturally, I tried

59 2 * * * : $(date +%Y%m%d) Backup Settings; ~/backup_settings.sh

but that doesn't result in the desired email subject, i.e. "20180519 Backup Settings". The $(...) code gets unevaluated. I don't want to run another script with email functionality that will then call backup_settings.sh. Is there a way of doing it using just Bash commands in crontab?


回答1:


The character % is special in the crontab and has to be escaped as \%:

59 2 * * * : $(date +\%Y\%m\%d) Backup Settings; "$HOME/backup_settings.sh"

From man 5 crontab on an Ubuntu system:

The entire command portion of the line, up to a newline or % character, will be executed by /bin/sh or by the shell specified in the SHELL variable of the crontab file. Percent-signs (%) in the command, unless escaped with backslash (\), will be changed into newline characters, and all data after the first % will be sent to the command as standard input.

Note, though, that cron will put the verbatim command of the cronjob in as the subject in any email that it sends, not the expanded command line.

To send an email with your own title, use mail explicitly:

59 2 * * * "$HOME/backup_settings.sh" | mail -s "$(date +\%Y\%m\%d) Backup Settings" myname

(where myname is the address you'd like to send the email to).



来源:https://stackoverflow.com/questions/50423725/date-in-crontab-email-subject

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!