Over the last few months I have really spent a lot of time working with Linux. Part of this work means that I have to set up automated systems that are able to log information, run scripts, gather data from sites, etc.

Luckily Linux comes with some really useful tools that allow for automated programs to be run. There are numerous configurations that one can use with crontabs in Linux which I am currently using.

However, when setting up these systems, I often ran into issues with how I configured the scripts, where they were stored, and how they were run.

In addition to this, cron doesn’t natively provide the ability to tell the user what happened when a cron job did (or didn’t) run.

The following template allows the user to set up cron tabs such that their outputs are placed in log files, such that debugging during the cron creation process and future failures can be captured for later debugging.

Users

The first issue that I came across was how the script is run and which user runs the script.

To access the crontab of the user currently logged in can be run with:

crontab -e

This opens the crontab file that has the list of cron jobs that are used in the machine and user 1 2.

Logging Output

Normally, you configure cron to email you when cron jobs fail, it also stores its logs in a distro specific folder.

I want to configure the cron tab so that it will send its output directly to a log file of my choosing, that way debugging can be made simpler and the logs can be directed into specific log files for each job. This cleans up the logging process as I can narrow down which process is causing issues without having to scroll through many entries.

The most simple way that I have found to log the output of cron jobs is the following:

*/1 * * * * /home/user/script.sh >> /home/user/script.log 2>&1

This will place the output from script.sh to script.log.

  1. Note: The cron job will be run as if it were being run by the user that the cron tab file is in. This means that it will run with the permissions given to that user, in addition to the path variables available to that user. 

  2. Also take care about where the cron job is being run from, this should guide you in how to format the relative paths that you use to run the different programs.