Question: I created a backup.sh shell script and added it to my crontab to execute it daily. How do I verify whether the backup cron script job ran successfully? Also, I have several echo statements inside my backup.sh shell script. How do I save the output of my script to a log file when it is executed as a cron job?

Answer: Let us say that you’ve added the backup.sh to your crontab as shown below to execute it at midnight every day.

$ crontab -e
59 23 * * * /home/john/bin/backup.sh

To verify whether the this job got executed successfully or not, check the /var/log/cron file, which contains information about all the cron jobs that gets executed in your system. As you see from the following output, john’s cron job got executed succesfully.

$ tail /var/log/cron
Oct  8 22:00:00 dev-db crond[18340]: (root) CMD (/bin/sh /home/root/bin/system_check &)
Oct  8 23:00:00 dev-db crond[20348]: (oracle) CMD (/bin/sh /home/oracle/bin/cleanup.sh &)
Oct  8 23:59:00 dev-db crond[20399]: (john) CMD (/bin/sh /home/john/bin/backup.sh &)

Cron log contains the following information:

Timestamp – The date and time when the cron job was executed
Hostname – The hostname of the server (For example, dev-db)
The cron deamon name and the PID. For example, crond[20399]
Username – The username under which this cron job got executed. For example, john.
CMD – Anything following this is the real command that got executed at that time.

If there are any echo statements inside the backup.sh, you might want to log those into a file. In general, if the backup.sh cron script throws any output (including errors), you might want to log those to a log file. To do this, modify the crontab entry and add the output and error redirection as shown below.

$ crontab -e
59 23 * * * /home/john/bin/backup.sh > /home/john/logs/backup.log 2>&1

In the above:

> /home/john/logs/backup.log indicates that the standard output of the backup.sh script will be redirected to the backup.log file.
2>&1 indicates that the standard error (2>) is redirected to the same file descriptor that is pointed by standard output (&1).
So, both standard output and error will be redirected to /home/john/logs/backup.log