0

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?

Spinor8
  • 1,587
  • 4
  • 21
  • 48

1 Answers1

4

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).

Kusalananda
  • 14,885
  • 3
  • 41
  • 52
  • Using your recommendation, I am getting the following in my email subject: Cron : $(date +%Y%m%d) Backup Settings; "$HOME/backup_settings.sh. So the comands runs but the date still doesn't appear in the subject. – Spinor8 May 19 '18 at 11:12
  • @Spinor8 Yes, because cron puts the command executed into the subject. There is to my knowledge no way to change that from a cron job. – Kusalananda May 19 '18 at 11:25