This tutorial aims to guide you on how to schedule shell scripts using Crontab. The Crontab is a simple yet powerful tool in Unix-like operating systems that enables you to automate tasks to run at specified times.
By the end of this tutorial, you will learn:
- What Crontab is and how it works
- How to create, edit, and manage cron jobs
- How to schedule a shell script to run at specific intervals
Prerequisites
You should be familiar with basic Unix/Linux command line syntax. Additionally, you should have a Unix/Linux environment to practice the examples given in this tutorial.
Crontab, short for 'cron table', is a configuration file that specifies shell commands to run periodically on a given schedule. The name 'cron' comes from the Greek word 'chronos', meaning 'time'.
Each line of a crontab file represents a job and follows a particular syntax to schedule the job. The syntax is as follows:
* * * * * command
Each asterisk can be replaced with:
Let's now dive into practical examples.
To edit the crontab file, we use the crontab -e
command. This command opens the crontab file in the default text editor.
crontab -e
Initially, this file will be empty. You can add your jobs one by one.
Let's say you want to schedule a shell script (script.sh
) to run every day at 12 PM. Here is how to do it:
# Open the crontab file
crontab -e
# Add the following line
0 12 * * * /path/to/script.sh
The above line means: "Run the script.sh file at 0 minutes (the beginning) of the 12th hour of every day, every month, every day of the week."
To list all the cron jobs currently scheduled for your user, use the crontab -l
command:
crontab -l
This will list all the jobs you have scheduled.
In this tutorial, we have learned about cron jobs and how to schedule them using the crontab command in Unix/Linux. We have seen how to create, edit, list, and understand the syntax of a cron job.
The next steps would be to explore more complex scheduling and using cron jobs to automate more tasks. You can learn more about advanced crontab options from the Crontab Guru website.
Exercise 1: Schedule a script to run every minute.
Solution: Open the crontab file (crontab -e
) and add the following line: * * * * * /path/to/script.sh
. This means the script will run every minute of every hour of every day.
Exercise 2: Schedule a script to run every Monday at 5 PM.
Solution: Open the crontab file (crontab -e
) and add the following line: 0 17 * * 1 /path/to/script.sh
. This means the script will run at 5 PM (17:00) every Monday.
Keep practicing with different schedules to become more comfortable with crontab!