crontab is a super useful tool used for regular background tasks like backups.
Create or edit a crontab entry using
crontab -e in the shell. Don't edit them directly. Use
crontab -e as the entry point.
Here is an example of a crontab entry:
0 10 */2 6-9 * ./path/to/backup.sh
A crontab entry has two parts:
- The scheduled recurring time to execute:
0 10 * * 1-5
- The command to be executed:
The time format is relative to the current time on your machine. From left to right:
- Minutes after the hour (0 to 59)
- Hour in 24 hour format (0 to 23)
- Day of the month (1 to 31)
- Month (1 to 12)
- Day of the week (0 to 7 or name e.g. Sun; 0 and 7 determine Sunday)
There are multiple types of specifiers you can use in each slot:
|a,b,c||At a, b and c|
|a-b||From a to b|
|*||first to last|
|a-d/x||From a to d with steps of x.
An example, where a script would run every other day at 10am from June through the end of September:
0 At the top of the hour 10 At 10am */2 Every other day 6-9 From June through the end of September * Every day of the week
All five fields can also be replaced by a single
||Run once i.e. at startup|
||Run once a year i.e.
||Run once a month i.e.
||Run once a week i.e.
||Run once a day i.e.
||Run once an hour i.e.
A command can be any command you would normally run in the shell. Everything must remain on one line, so I would recommend using
&& and shell scripts.
List your current crontab file using
crontab -l. This is useful for automated backups using crontab :).
- The crontab file MUST end with a newline.
- If using a script, ensure your script file you want to execute does not have an extension. e.g.
./backupwill run but
./backup.shwon't. Add a shebang to your script file, like
#!/bin/zshfor shell or
#!/usr/bin/env python3for Python 3.
- To ensure your
$PATHand other aliases are present, preface your commands with
/bin/bash -l -c(or whatever shell) and encapsulate your command in single quotes. e.g.
/bin/zsh -l -c './build/'.
Last modified: 202212070107