Linux crontab File
Linux crontab File
In Linux, scheduled tasks (also called cron jobs) are managed by the cron daemon. The /etc/crontab
file is a system-wide configuration file that allows administrators to automate the execution of scripts and commands at specific times or intervals. Unlike user-specific cron jobs (configured using crontab -e
), the /etc/crontab
file supports specifying the user who will execute the command.
Imagine having a personal assistant who automatically runs tasks for you at specific times, like backing up files or updating software. The /etc/crontab file in Linux is like a set of instructions for this assistant, telling the system when and how to execute scheduled tasks for all users.
What is the /etc/crontab File?
The /etc/crontab
file is a system-wide configuration file used to schedule recurring tasks (called cron jobs) on Linux systems. Unlike user-specific cron jobs, this file allows administrators to define tasks for any user account on the system. It is used to execute commands as different users at specified times without requiring each user to define their own cron jobs.
Why Use /etc/crontab?
The primary purpose of the /etc/crontab
file is to schedule tasks such as system maintenance, log rotation, backups, or running scripts automatically at predefined intervals. Unlike user crontabs, this file requires an additional field to specify the user under whom the command will run.
- Schedule system-wide maintenance tasks (e.g., log cleanup, updates).
- Run scripts or commands as specific users (e.g., root, www-data).
- Automate repetitive processes without manual intervention.
Edit the file
You can use the vi editor to edit the file.
$ sudo vi /etc/crontab
Since /etc/crontab is a system file, you need sudo (superuser privileges) to modify it.
Press i to insert, edit as needed, then press Esc, type :wq, and hit Enter.
Structure of the /etc/crontab File
Each line defines a cron job in this format:
# m h dom mon dow user command * * * * * root /path/to/script.sh
Each field represents:
- m – Minute (0-59)
- h – Hour (0-23)
- dom – Day of the month (1-31)
- mon – Month (1-12)
- dow – Day of the week (0-7, where both 0 and 7 represent Sunday)
- user – The user under whom the command runs
- command – The script or command to be executed
Example: Scheduling a Script
To run /home/userid/script
every minute as userid
:
* * * * * userid /home/userid/script
Note: *
means “every” (e.g., every minute, every hour).
Scheduling Examples
Below are some examples of how to schedule a script using the /etc/crontab
file:
Daily backup. Run a script every day at 2:30 AM
30 2 * * * root /home/testingdocs/backup.sh
Run a script every hour
0 * * * * userid /scripts/hourly-task
Run a script every Monday at 5:00 PM
0 17 * * 1 root /home/userid/weekly_report.sh
Every 10 minutes
*/10 * * * * root /scripts/monitor-service