Unable to execute command in cron

I was trying to configure rsync to backup a directory every day with the name of current day.

rsync --verbose --stats --compress --recursive /home/alpha/ /var/backups/alpha/`date +"%a"`

Above command is working fine and is syncing data in Mon directory. But when I copy the same command in cron it is not working

13 16 * * * rsync --verbose --stats --compress --recursive /home/alpha/ /var/backups/alpha/`date +"%a"`

But when I remove `date +"%a"` part from cron it works.
Why cron is not executing `date +"%a"`?


Solution 1:

The % sign must be escaped with \, since it is an alternate way to end a command in crontab.

The "sixth" field (the rest of the line) specifies the command to be run. 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 cronfile. 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.

So your crontab line should look like:

13 16 * * * rsync --verbose --stats --compress --recursive /home/alpha/ /var/backups/alpha/`date +"\%a"`

Sources:

  • https://unix.stackexchange.com/questions/29578/how-can-i-execute-date-inside-of-a-cron-tab-job
  • https://linux.die.net/man/5/crontab

Solution 2:

You can also use:

13 16 * * * bash -c "rsync --verbose --stats --compress --recursive /home/alpha/ /var/backups/alpha/`date +'%a'`"