Cron jobs are the unsung heroes of system administration, quietly executing tasks on a schedule.

Let’s see one in action. Imagine you have a script, ~/scripts/backup.sh, that backs up your important files. To run this every day at 2 AM, you’d edit your crontab:

crontab -e

This opens your personal crontab file in your default editor. You’d add a line like this:

0 2 * * * /home/youruser/scripts/backup.sh

Here’s what this means:

  • 0: The minute (00 past the hour).
  • 2: The hour (2 AM, in 24-hour format).
  • *: The day of the month (every day).
  • *: The month (every month).
  • *: The day of the week (every day of the week).
  • /home/youruser/scripts/backup.sh: The command to execute.

The system then takes over. When the clock strikes 2:00 AM, the cron daemon (crond) reads its configuration files (including your crontab) and launches a new process to run the specified command. It’s essentially a highly reliable, built-in scheduler.

The real power of cron lies in its simplicity and ubiquity. It’s available on virtually every Unix-like system. You can schedule anything from simple commands to complex shell scripts. Need to clear out old log files daily? Want to fetch data from an API every hour? Cron can handle it.

Internally, the crond process starts at boot time and continuously checks the system’s crontab files (typically in /etc/crontab and directories like /etc/cron.d/) and user-specific crontabs (stored in /var/spool/cron/crontabs/). It compares the current time with the schedule entries and executes jobs when the time matches.

The exact levers you control are the five time fields and the command itself. You can get very granular, like running a job only on weekdays between 9 AM and 5 PM, or only on the first day of every month. For example, to run a script every Monday at 5 PM:

0 17 * * 1 /home/youruser/scripts/weekly_report.sh

Here, 17 is 5 PM, and 1 represents Monday (with Sunday being 0 or 7).

Many users are unaware that cron jobs run with the environment variables of the user who owns the crontab. This means if your script relies on specific PATH settings or other environment variables, you might need to define them within the crontab itself or source a profile file at the beginning of your script. For instance, if your script needs /usr/local/bin in its path, you could add:

PATH=/usr/local/bin:/usr/bin:/bin
0 2 * * * /home/youruser/scripts/backup.sh

This ensures that commands located in /usr/local/bin are found when the cron job executes.

Beyond the basic crontab, systems often have directories like /etc/cron.hourly/, /etc/cron.daily/, /etc/cron.weekly/, and /etc/cron.monthly/. Placing an executable script in one of these directories will cause it to run automatically at the corresponding interval, managed by the system’s main cron configuration.

The next challenge is often managing cron job output and errors effectively.

Want structured learning?

Take the full Bash course →