Bash Scripting — Scheduling Tasks with Cron
What You’ll Learn in This Chapter
Welcome to Chapter 30 — Scheduling Tasks with Cron! 🕐
Imagine you need a script to run every night at midnight — backing up a database, rotating logs, or sending a daily report. You wouldn’t want to set an alarm and run it manually every single day, right?
That’s exactly what cron is for. It’s the time-based job scheduler built into every Linux system, and mastering it is a must-have skill for any DevOps engineer or sysadmin.
Why Cron Matters
In the real world, most production servers rely on cron for:
- Automated backups — database dumps, file system snapshots
- Log rotation — compress and archive old logs
- Health checks — periodic pings, disk-space alerts
- Data pipelines — ETL jobs, report generation
- Certificate renewal — Let’s Encrypt auto-renewal
- Cleanup tasks — purge temp files, expired sessions
Without cron, you’d need an external orchestrator or a long-running daemon just to run periodic tasks. Cron keeps it simple, reliable, and native to the OS.
Chapter Roadmap
This chapter is split into focused lessons so you can learn step by step:
| # | Lesson | What You’ll Learn |
|---|---|---|
| 1 | crontab Syntax | The 5-field format, special characters, common patterns |
| 2 | cron Expressions | Real-world scheduling examples and crontab.guru |
| 3 | crontab -e and Shortcuts | Editing, listing, removing crontabs, @reboot and friends |
| 4 | cron Environment Limitations | PATH pitfalls, MAILTO, SHELL, sourcing profiles |
| 5 | Logging Cron Output | Redirect output, timestamp logs, syslog, log rotation |
| 6 | Practice Exercises | 5 hands-on challenges from easy to advanced |
Prerequisites
Before diving in, you should be comfortable with:
- Writing and executing Bash scripts (
chmod +x,./script.sh) - Basic file redirection (
>,>>,2>&1) - Environment variables and
PATH - Using a terminal text editor (
nano,vim, orvi)
If any of these feel shaky, revisit the earlier chapters — then come back here. We’ll be waiting. 😊
A Quick Taste
Here’s the simplest possible cron job — it writes the current date to a file every minute:
# Open your crontab for editing
crontab -e
# Add this line:
* * * * * /bin/date >> /tmp/cron_test.log
After saving, check the log after a couple of minutes:
cat /tmp/cron_test.log
Expected output (timestamps will differ):
Sun Jun 1 19:38:01 IST 2025
Sun Jun 1 19:39:01 IST 2025
If that worked — congratulations, you just scheduled your first cron job! Now let’s learn exactly how it works.
Key Terminology
| Term | Meaning |
|---|---|
| cron | The daemon (background service) that runs scheduled jobs |
| crontab | The command and the file that holds a user’s scheduled jobs |
| cron job | A single scheduled task (one line in a crontab) |
| cron expression | The 5-field time pattern (* * * * *) |
Let’s Get Started
Head over to the first lesson: crontab Syntax →
Happy scheduling! 🚀