cron
is a time-based job scheduler in Unix-like operating systems that allows users to run scripts or commands at specified times and intervals. The crontab
(cron table) is a file where users define these scheduled tasks.
crontab
Format┌──────── Minute (0 - 59) │ ┌────── Hour (0 - 23) │ │ ┌──── Day of the month (1 - 31) │ │ │ ┌── Month (1 - 12) │ │ │ │ ┌── Day of the week (0 - 7, Sunday is both 0 and 7) │ │ │ │ │ * * * * * command-to-execute
30 2 * * * /path/to/script.sh
0 17 * * 1 /usr/bin/python3 /home/user/script.py
0 0 1 * * /usr/bin/backup.sh
*/15 * * * * /home/user/check_status.sh
crontab
Jobscrontab -l
crontab -e
crontab -r
Check logs with:
grep CRON /var/log/syslog
Capture output of a cron job:
0 0 * * * /home/user/script.sh >> /home/user/cron.log 2>&1
In the above command, 2>&1
redirects standard error (stderr, file descriptor 2) to standard output (stdout, file descriptor 1). This ensures that both normal output and error messages are captured in the same log file.
@
Macros for Common Schedules@reboot
→ Runs at startup@hourly
→ Runs every hour@daily
→ Runs once a day@weekly
→ Runs once a week@monthly
→ Runs once a month@yearly
→ Runs once a yearExample: @daily /home/user/cleanup.sh
Check if a cron job is set:
crontab -l | grep my_script.sh
Run the command manually to test:
/bin/bash /home/user/my_script.sh
cron
with Environment VariablesSince cron
does not load your usual shell environment, explicitly specify paths:
PATH=/usr/local/bin:/usr/bin:/bin 0 3 * * * /home/user/script.sh
To schedule a job for another user (as root):
sudo crontab -u username -e
Always test your cron job manually before scheduling it, and log the output for debugging! 🚀