Crontab in Linux: Examples and Useful Commands
Crontab is used in Linux to schedule tasks that run periodically at specified times or intervals. This tool is essential for automating repetitive tasks like backups, updates, and system monitoring.
Crontab Syntax
The general format for a crontab entry:
* * * * * command_to_be_executed
- - - - -
| | | | +----- Day of the week (0-7, both 0 and 7 represent Sunday)
| | | +------- Month (1-12)
| | +--------- Day of the month (1-31)
| +----------- Hour (0-23)
+------------- Minute (0-59)
Crontab Commands
# Viewing and Editing Crontab
crontab -l # View current crontab
crontab -e # Edit crontab in default editor
# Removing Crontab
crontab -r # Remove entire crontab (delete all cron jobs)
# Crontab for Another User
sudo crontab -u username -e # Edit crontab for a specific user
sudo crontab -u username -l # View crontab for a specific user
Crontab Examples
- Every minute:
* * * * * /path/to/command
- Every hour at 0 minutes:
0 * * * * /path/to/command
- Every day at midnight:
0 0 * * * /path/to/command
- Every Sunday at 5:00 AM:
0 5 * * 0 /path/to/command
- First day of every month at midnight:
0 0 1 * * /path/to/command
- Every weekday at 3:00 PM:
0 15 * * 1-5 /path/to/command
- Every 15 minutes:
*/15 * * * * /path/to/command
- On the 1st and 15th of every month at 2:30 AM:
30 2 1,15 * * /path/to/command
- Every 5 minutes during business hours (9 AM – 6 PM):
*/5 9-18 * * 1-5 /path/to/command
- Backup every Sunday at midnight:
0 0 * * 0 /path/to/backup.sh
Advanced Crontab Usage
- Redirect output to a file:
* * * * * /path/to/command >> /path/to/logfile.log 2>&1
- Set environment variables:
PATH=/usr/bin:/bin:/usr/sbin:/sbin
SHELL=/bin/bash
- Run a command as a specific user:
* * * * * sudo -u username /path/to/command
- One-time cron job:
echo "0 6 10 1 * /path/to/command" | crontab -
Cron Logs
Check cron logs with:
cat /var/log/syslog | grep cron
Conclusion
Crontab is an essential tool in Linux for automating tasks that need to run on a recurring schedule. Understanding how to use cron expressions effectively is key to leveraging its full potential. This guide covers the basics and advanced techniques, including practical examples to help you automate a wide range of tasks on your Linux system.
By mastering crontab, you can significantly reduce manual tasks, improve system efficiency, and ensure important processes run on time without fail.