问题
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 theSHELL
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