How to check if cron job works?

I use crontab -e without sudo to edit cron jobs and add the following line there -

20 22 23 10 * date "+%Y-%m-%d %H:%M:%S" >> ~/Documents/log.txt

then I check the log file and it doesn't contain the date and time.

I tried to edit crontab as root, but it also doesn't update the file. What could be wrong here? Is there any way to see the log of cron jobs execution?

P.S. Update crontab created under root:

0/5 * * * * /bin/date "+%Y-%m-%d %H:%M:%S" >> /tmp/log.txt
0/5 * * * * echo >> /tmp/log2.txt

log2.txt is created now.


Solution 1:

Your cron error message are sent to the mail account of the user that is running the cron job.

Type mail at the command line to see the messages. For a list of mail commands, see man mail.

You should be getting mail with an error message something to the effect of:

/bin/sh: -c: line 0: unexpected EOF while looking for matching `"'
/bin/sh: -c: line 1: syntax error: unexpected end of file

As for you command and why it's not working, it's because the "%" sign is a "newline" character, meaning that it tells the shell to "go to the next line." So, after it encounters the first "%" it goes to the next line and it never sees the rest of the command. This is confirmed by the "unexpected EOF while looking for the matching ' " '(double quote).

The local man page for crontab (man crontab)is quite sparce with details and I am speculating it's because cron has been deprecated for launchd1. However, the crontab manpage from developer.apple.com explains it

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. The command can optionally be prefixed by "@AppleNotOnBattery" to tell cron not to run the command when functioning on battery power. For example, the "sixth" field when using this option would appear something like "@AppleNotOnBattery /usr/bin/touch /tmp/foo"


Your fix:

So, what you need to do, is "escape" the "%" character with a backslash (\) so that it tells it to interpret it literally.

Your command should be:

0/5 * * * * /bin/date "+\%Y-\%m-\%d \%H:\%M:\%S" >> /tmp/log.txt

1 From man crontab: (Darwin note: Although cron(8) and crontab(5) are officially supported under Darwin, their functionality has been absorbed into launchd(8), which provides a more flexible way of automatically executing commands. See launchctl(1) for more information.)