Using Cron to Automate Linux Tasks
Linux is one of the most flexible and useful operating systems available. One of the tools that places Linux at the top of the flexibility and usability scale is cron. The cron system allows you to automate tasks without the aid of third party software. But because few know how to use cron, it seems too complex to bother with. Not so. The cron system is actually quite easy to use. Let's take a look at cron.
The cron system works by reading various crontab files either found in a users' directory or within the /etc directory. These cron files can be edited with either the crontab command or by editing the various files within /etc. Only the root user can edit the /etc files because those files (found in the subdirectories /etc/cron.d, /etc/cron.daily, /etc/cron.hourly, /etc/cron.weekly, /etc/cron.monthly) are used for system services. Instead of focusing on system services, I will illustrate how to automate the execution of a user-created bash script.
This imaginary bash script will be called myscript.sh. This script will be housed in /home/jlwallen/ and will have executable permission (by way of chmod u+x myscript.sh). What we want to do is automate the execution of this script so that it executes once per day at the same time every day (we'll say 7am).
Before we get into editing with crontab we first need to chat about how cron views time.The cron system looks at time like this:
- Hour (0-23)
- Day of the month (1-31)
- Month (1-12)
- Day of the week (0-6 with Sunday being 0)
The structure of cron time looks like this:
Minute Hour Day of month Month Day of the week
The trick for cron is that when you do not have an entry for a section you add an "*". So the time entry for a cron job that should run at 7am every day of the week would look like:
0 7 * * *
That is not the complete cron entry, just the time portion. Now, on to editing with crontab.
Users edit their cron entries with the crontab command. The crontab command has a few switches:
- e - Edit your crontab
- l - List your crontab
- r - Delete all crontab entries
To add a new crontab entry enter the command crontab -e which will place you in the vi text editor with your user crontab file opened. If you're not familiar with vi I'll give you the crash course as we edit the crontab.
First click the "i" key to go into the insert mode. You can now add text. Enter the cron entry to run the myscript.sh every day at 7am. This entry will look like:
* 7 * * * ~/myscript.sh
Now hit the Esc key to get out of the insert mode. Once out of insert mode you need to write the file and quite crontab. To do this hit the ":" key followed by "wq" (for write and quite). Finish the job by hitting the Enter key.
You should see "crontab: installing new crontab" at your bash prompt.
Congratulations, you've just created your first cron job!Advertisement