Crontab Command on Linux with Examples
The crontab
command in Linux is a powerful tool used for scheduling tasks to be executed automatically at specified times or intervals. It stands for “cron table,” utilizing the cron daemon to execute tasks based on the schedule defined in the crontab files. This guide aims to provide an in-depth look at the crontab
command, covering basic usage, advanced options, and common mistakes to avoid.
Introduction to Crontab
The crontab command utilizes the cron daemon to execute cron jobs at fixed times, dates, or intervals. The word “cron” originates from “chronos”, the Greek word for time. The cron service runs in the background and checks the crontab files every minute to determine if there are scheduled jobs due for execution.
Crontab provides granular control to schedule tasks down to the minute. System administrators often use crontab for automating repetitive jobs like rotating log files, updating directories, backing up data, and more. It can also be used by regular users to run personal scripts.
Understanding Crontab Syntax
The crontab syntax consists of two parts – the cron schedule and the command to execute.
The basic format is:
* * * * * command to execute - - - - - | | | | | | | | | ----- Day of week (0 - 7) (Sunday=0 or 7) | | | ------- Month (1 - 12) | | --------- Day of month (1 - 31) | ----------- Hour (0 - 23) ------------- Minute (0 - 59)
Let’s break this down further:
- Minute – The minute field specifies the minutes of the hour (0 to 59)
- Hour – The hour field sets the hour of the day (0 to 23)
- Day of Month – The day of month defines the date (1 to 31)
- Month – The month field sets the month (1 to 12)
- Day of Week – The day of week sets the day (0 to 7, 0 or 7 is Sunday)
These time and date values allow you to precisely schedule when the job should run. The command is specified after the time fields.
Managing Crontab Files
To view, edit, or create cron jobs, you can manage the crontab files. Each system user has their own crontab file location.
View Existing Jobs
To view your existing cron jobs, run:
crontab -l
This will list the cron tasks scheduled for the current user.
Edit Crontab File
To edit or create a new crontab file, use:
crontab -e
This will open the crontab file for the logged-in user in the default text editor (usually nano or vim).
Here you can add new jobs by specifying the cron schedule and command. Ensure to save the file after making changes.
# Edit this file to introduce tasks to be run by cron * * * * * /path/to/script.sh
The above cron job will run the script every minute.
Create User Cron Jobs
To create or modify the crontab for a different user, use -u
:
crontab -u user1 -e
This edits the crontab of “user1”. Useful for setting up jobs for other users.
Now that we understand the basics of crontab syntax and how to access the files, let’s move on to more advanced functionalities.
Leveraging Advanced Crontab Options
Crontab provides several useful options to create more flexible and customized scheduled jobs.
Special Strings for Simplifying Schedules
Manually specifying the 5 time and date fields every time can be tedious. Crontab offers special strings to define common recurring intervals.
For example:
@hourly: Run once every hour (0th minute) @daily: Run once a day at midnight @weekly: Run once a week (Sunday midnight) @monthly: Run once a month (1st of month midnight) @yearly: Run once a year (1st of Jan, midnight) @reboot: Run once at startup
These strings simplify crontab schedules significantly.
Setting Environment Variables
You can set environment variables for your cron jobs using the syntax:
VAR=value
This is useful to define specific settings, directories, and configs for the context of that particular job.
For example:
BACKUP_DIR=/home/user/backups LOG_FILE=/var/log/mycron.log 0 2 * * * /scripts/backup.sh > $LOG_FILE 2>&1
Here we set custom variables, then reference them in the cron job.
Redirecting Output to a File
By default, the output of cron jobs is mailed to the user. To write the output to a file instead, redirect stdout and stderr:
0 * * * * script.sh > /tmp/job.log 2>&1
This will append both standard output and standard error to the /tmp/job.log
file.
Setting the User Environment
Use the su
command to schedule jobs for a different user account:
0 * * * * su - user1 -c "/path/to/user1_script.sh"
This will switch context and run the script as “user1” user at the 0th minute.
Similarly, you can use sudo
to schedule tasks with superuser privileges.
Commenting Inside Crontab
It’s good practice to add comments explaining what a job does and when it runs:
# Nightly backup 0 2 * * * /scripts/backup.sh
Comments begin with # symbol, everything after is ignored by cron.
Now that you understand the extended features of crontab, let’s go over some common issues and troubleshooting techniques.
Debugging Crontab: Common Issues and Fixes
When creating cron jobs, you might run into errors preventing the task from running. Here are some frequent problems and ways to debug them.
Script Fails to Run
First, test the script manually from the command line to ensure there are no errors. Then check these:
- Permissions – Use
chmod +x your_script.sh
to make sure execute permission is enabled. - Paths – Specify the absolute path to the script in the cron job, as cron has a limited environment.
- Variables – Define necessary environment variables like PATH explicitly in the crontab.
Job Not Running As Expected
- Verify the schedule is correct. Recheck the time/date fields and ensure they align with when you expect the job to run. Use the special strings to prevent issues.
- Check cron log files at
/var/log/cron
or/var/log/syslog
for any recorded errors. - Redirect output to a file and inspect that file to see if errors occurred.
Job Runs Multiple Times
If your job keeps running repeatedly, ensure you:
- Didn’t schedule the job multiple times. View your crontab to double check.
- Don’t have overlapping schedule rules, e.g.
@daily
+ a rule for 2AM. - Another user doesn’t have the same job scheduled.
Carefully inspecting your crontab syntax, logs, script errors, and output will help identify and resolve surprising cron behavior.
Best Practices for Crontab
Here are some tips for running cron jobs effectively:
- Clearly comment jobs explaining what they do and when they run.
- Use absolute paths for commands and scripts.
- Redirect output to a dedicated log file for monitoring job activity.
- Set environment variables necessary for the context.
- Limit cron usage for intensive jobs, as they can overload a system if not managed.
- Schedule backups during non-peak times to avoid performance impact.
- Validate jobs manually after creating them.
Adopting these crontab best practices will ensure your scheduled jobs run reliably for important automation.
Conclusion
Crontab is an invaluable tool for automating Linux system administration tasks with precision scheduling. With its extensive options for customizing when jobs run as well as granular control over times and intervals, crontab can eliminate manual repetition of critical system upkeep. This guide covered the core crontab concepts from basic syntax to advanced functionalities like environment variables and output redirection, to troubleshooting techniques for addressing common cron issues. With this comprehensive understanding, you can now create automated cron jobs to handle time-based jobs reliably. Refer to this reference for leveraging crontab or share it as a resource when training team members on unlocking automation with cron.