Automate tasks in Linux using cron

Cron is a simple yet powerful tool for automating tasks on Linux, macOS, BSD, and other Unix systems.


Most operating systems support some form of scheduled activities. Cron jobs are a simple yet powerful way to schedule automatic execution of commands or scripts on Linux or Unix (BSD, macOS, etc.).

Here is an example of a cron job that appends a line with the current date and time to a file every hour:

* 1 * * * /bin/date >> /tmp/date_and_time.txt

The schedule for the various jobs is stored in a configuration file called "crontab". The order of the fields in a crontab entry is:

  • Minute

  • Hour

  • Day of month

  • Month

  • Day of week

  • Command

Allowed values for the different fields are:

Minute        0 to 59
Hour          0 to 23
Day of month  1-31
Month         1-12
Day of week   0-6
Command       The command to execute

Example of a cron job for Magento

Below is a slightly more advanced example of a cron job for a Magento installation that should run every day at 23:30. The purpose of the cron job is to empty the directory that holds session files, which are generated continuously. Those files consume unnecessary disk space and can eventually fill the disk. We also describe what we intend to do with the result.

Here’s what our cron job looks like:

What does the cron job do?

We want to find all files matching sess* in the directory /var/www/magento/var/session/ that are older than 14 days. We want the cron job to delete all those files.

Examples of how to handle the resulting output

If you want to receive email confirmation that the cron job has run, add the following line to your crontab:

If you want to write the cron job’s log to a file, use the following syntax:

If you want the cron job to run every 30 minutes, suppress all output (both stdout and stderr), and prevent any email notifications for completed or missed runs:

For an older version of Bash, you write it like this instead:

Last updated

Was this helpful?