Table of Contents
Scheduled tasks, commonly known as cron jobs, are a powerful feature in Linux for automating repetitive tasks. Here’s a guide on how to create and manage cron jobs:
Viewing Existing Cron Jobs:
- To list the existing cron jobs for the current user, use:
crontab -l
- To list cron jobs for a specific user (requires sudo privileges):
sudo crontab -u <username> -l
Editing Cron Jobs:
- To edit the current user’s cron jobs, use:
crontab -e
- To edit cron jobs for a specific user (requires sudo privileges):
sudo crontab -u <username> -e
Cron Job Syntax:
A cron job follows the syntax:
* * * * * command_to_be_executed
- The five asterisks represent minute (0-59), hour (0-23), day of the month (1-31), month (1-12), and day of the week (0-6, where Sunday is 0 or 7).
Examples:
- Run a script every day at 3 AM:
0 3 * * * /path/to/script.sh
- Run a command every hour:
0 * * * * /path/to/command
- Run a job every Monday at 2 PM:
0 14 * * 1 /path/to/job.sh
- Run a job on the 15th of every month at 5:30 AM:
30 5 15 * * /path/to/monthly_job.sh
- Run a job every weekday at 8 AM and 6 PM:
0 8,18 * * 1-5 /path/to/daily_job.sh
Special Strings:
- @reboot: Run the job at startup.
@reboot /path/to/startup_script.sh
- @daily, @weekly, @monthly: Run the job daily, weekly, or monthly.
@daily /path/to/daily_job.sh
Removing Cron Jobs:
- To remove all current user’s cron jobs:
crontab -r
- To remove a specific user’s cron jobs (requires sudo privileges):
sudo crontab -u <username> -r
Tips:
- Redirect Output to a Log File:
0 3 * * * /path/to/script.sh >> /path/to/logfile.log 2>&1
- Environment Variables:
SHELL=/bin/bash PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
- Edit crontab Without Opening an Editor:
(crontab -l ; echo "0 3 * * * /path/to/script.sh") | crontab -
Remember, cron jobs run in the context of the user who creates them. Ensure that the user has the necessary permissions and that paths to scripts and commands are absolute or set correctly.