
What is Cron?
Cron is a time-based job scheduler in Linux and other Unix-like operating systems. It allows users to schedule tasks (commands or scripts) to run automatically at specified times and intervals.
Think of cron as your system’s alarm clock.
Each scheduled job is called a cron job.
Cron runs in the background as a daemon (crond
).
Why Use Cron with Bash?
Bash scripts let you define tasks (like backups, monitoring, reports). Cron makes sure those tasks run on schedule without manual effort. Together, they:
✅ Save time
✅ Reduce errors from manual execution
✅ Ensure consistency
✅ Enable 24/7 unattended automation
Cron Syntax Explained
A cron job follows this pattern:
$$
- * * * * command_to_execute
- - - - -
| | | | |
| | | | +—- Day of week (0-6, Sunday=0)
| | | +—— Month (1-12)
| | +——– Day of month (1-31)
| +———- Hour (0-23)
+———— Minute (0-59)
$$
Examples:
0 2 * * * /home/user/backup.sh
→ Run backup.sh
at 2:00 AM daily.
*/5 * * * * /home/user/ping_test.sh
→ Run every 5 minutes.
0 9 * * 1 /home/user/report.sh
→ Run every Monday at 9:00 AM.
Viewing and Editing Cron Jobs
View jobs:
$$
crontab -l
$$
Edit jobs:
$$
crontab -e
$$
Remove all jobs:
$$
crontab -r
$$
Each user has their own crontab file to manage jobs.
Automating Bash Scripts with Cron
Suppose you have a script to back up your documents:
$$
#!/bin/bash
tar -czf /home/user/backups/docs_$(date +\%F).tar.gz /home/user/Documents
$$
Make it executable:
$$
chmod +x backup.sh
$$
Schedule with cron:
$$
crontab -e
$$
Add this line:
$$
0 1 * * * /home/user/backup.sh
$$
Now your files back up automatically every day at 1 AM.
Special Cron Keywords
Instead of numbers, cron provides shorthand keywords:
@reboot
→ Run once at system startup
@daily
→ Run once a day (midnight)
@hourly
→ Run once every hour
@weekly
→ Run once a week
@monthly
→ Run once a month
Example:
$$
@reboot /home/user/startup_script.sh
$$
Logging & Debugging Cron Jobs
Cron jobs run silently in the background, so debugging is crucial.
Redirect output to a log file:
$$
0 2 * * * /home/user/backup.sh >> /home/user/backup.log 2>&1
$$
Check system logs:
$$
grep CRON /var/log/syslog # Ubuntu/Debian
grep CRON /var/log/cron # CentOS/RHEL
$$
Real-World Use Cases
System Maintenance
- Clear temp files daily.
- Rotate logs weekly.
Backups
Monitoring & Alerts
Reports & Data Processing
Common Pitfalls
⚠️ Forgetting PATH → Cron jobs run with a limited environment. Always use absolute paths.
Example:
Instead of python myscript.py
, use /usr/bin/python3 /home/user/myscript.py
.
⚠️ No output logs → Without redirection, errors disappear. Always log outputs.
⚠️ Permissions → Make sure scripts are executable and accessible to cron’s user.
⚠️ Overlapping jobs → If a job takes longer than its interval, you might have duplicate processes. Use locks to prevent overlap.