Automation is the backbone of DevOps, and cron jobs are one of the simplest yet most powerful tools for scheduling repetitive tasks in Linux. But hereβs the golden rule : Never run cron without logs.
Without logs, youβre flying blind β you wonβt know if your job succeeded, failed, or silently broke.
π What is a Cron Job?
Cron is a time-based job scheduler in Unix/Linux.
It runs commands or scripts at specified intervals (minutes, hours, days).
Perfect for tasks like backups, monitoring, cleanup, or reporting.
β
Example: Disk Usage Monitoring with Logging
Hereβs a production-ready cron job:
*/5 * * * * /home/ubuntu/disk.sh >> /home/ubuntu/disk.log 2>&1
*/5 * * * * β Run every 5 minutes
/home/ubuntu/disk.sh β Script to check disk usage
>> /home/ubuntu/disk.log β Append standard output to log file
2>&1 β Redirect errors to the same log file
π This ensures both success and failure messages are captured.
π‘οΈ Why Logging Matters
Observability β Know what happened at each run.
Debugging β Errors are visible in logs.
Auditing β Historical record of job execution.
Reliability β Prevents silent failures.
β‘ Common Mistake: Typo in Service Name
A real-world example you might encounter:
ubuntu@ip-172-31-39-174:~/shell-script-learnings$ sudo systemctl stop corn
Failed to stop corn.service: Unit corn.service not loaded.
π The error happened because the service name is cron, not corn.
Correct command:
sudo systemctl stop cron
sudo systemctl start cron
sudo systemctl status cron
π Managing Cron Jobs
1. Add a Cron Job
crontab -e : Paste your job line, save, and exit.
2. List Current Cron Jobs
crontab -l
3. Remove a Specific Cron Job
Open crontab: crontab -e
Delete the line corresponding to the job, Save and exit.
4. Delete All Cron Jobs
crontab -r
β οΈ This wipes the entire crontab for the user.
π Production Enhancements
Timestamps in logs:
*/5 * * * * echo "$(date) - Running disk.sh" >> /home/ubuntu/disk.log 2>&1; /home/ubuntu/disk.sh >> /home/ubuntu/disk.log 2>&1
Log rotation (prevent infinite growth):
Create /etc/logrotate.d/disk:
Code:
/home/ubuntu/disk.log {
daily
rotate 7
compress
missingok
notifempty
create 644 ubuntu ubuntu
}
π― Conclusion
Cron jobs are deceptively simple but incredibly powerful. The difference between a hobby script and a production-grade job is logging and management.
Always log output and errors.
Monitor logs with rotation.
Manage jobs cleanly with crontab -e, crontab -l, and crontab -r.
Top comments (0)