How to Set up and Use Crontab in Ubuntu/Linux


Crontab is the file that manages and maintains the cronjobs on Ubuntu/Linux. The cronjobs are the automated tasks scheduled to execute/run at the specific schedule mentioned in the file. The cronjob contains any Linux-based command or the shell script’s path to be executed at a specific time.

Cronjobs are effective when you are working on a server. With cronjobs, you can create an automatic backup of the important files/database, generate/submit the reports, or perform automated execution-related activity at a scheduled time.

In today’s post, we will demonstrate the detailed working, and usage of the Ubuntu Crontab/Cronjobs on Ubuntu/Linux.

Prerequisites: Install Cron and Activate the Service

Before starting, it is recommended to ensure the latest version of the cron utility is installed on your system and the cron service is running too. Let’s ensure this:

sudo apt install cron

Activate (or verify the status) of the cron as follows:

sudo systemctl start cron 
sudo systemctl status cron

How Does Cron Work in Ubuntu/Linux

The crontabs as discussed store the cron jobs. Crontabs either contain user-specific or system-wide jobs. The user-specific cronjobs are stored in the “/var/spool/cron/crontabs” whereas the system-wide cronjobs are stored at the “/etc/crontabs”.

Irrespective of the cronjob category, the cronjob follows the below-stated syntax:

Syntax of the Cronjob

The syntax of the cronjob is as follows:

MIN H DOM MON DOW COMMAND/SCRIPT

The syntax values are:

  • MIN (Minutes): 0-59
  • H (Hour): 0-23
  • DOM (Day of the Month): 1-31
  • DOW (Day of a Week): 0-6 or SUN-SAT
  • MON (Month): 1-12 or JAN-DEC
  • COMMAND/SCRIPT: Any Linux-based command or script’s path.

Operators in the Cronjob

The above syntax refers to running the specific command at one time only. What about running a job multiple time? In that case, you need to separate the values with a comma, as we did here with the minute’s parameter.

MIN1,MIN2,MIN3 H D COMMAND

The syntax shows that the job will run at three different minutes while the other parameters remain the same.

Apart from this comma, there are other characters as well, which serve the specific purpose while creating/modifying cronjobs:

Operators Description/Usage Example Syntax
Asterisk (*) To include all the possible values of that field (minute, hour, day, etc) * * * MON DOW COMMAND
Hyphen (-) Between Values To Specify a range of values, 1-3 (for any entry) 0-5 H DOM MON DOW COMMAND
Separator (/) To divide the specific field into specific intervals. */12 H DOM MON DOW COMMAND
Last (L) To be used in the DOM (Last day of Month) and DOW (Last day of the week) * * L * L COMMAND
Weekday (W) Nearest Weekday with respect to the DOM. * * 5W * * COMMAND

Nearest Weekday to the 5th of every month

Hash (#) Applicable to Day of the Week to determine the day of the month. * * * * 6#3 COMMAND

Third Saturday of the Month

Question Mark (?) Applicable to DOM and DOW. Put ? in one of the fields to get the random value. “No Specific Value” * * 3 * ? COMMAND

Selecting 3rd day of the week irrespective of the day of the week.

Special Strings in Cronjobs

Cron does provide a list of special strings that are used in the cronjobs to run them once in an hour, day, week, month, or year. These strings are used in place of the first five fields of the cronjob “unit of time fields”. Let’s check the exact usage and syntax:

Special Strings Description/Usage Example Syntax
@hourly Runs one time in an hour @hourly Command/Script
@daily

@midnight

Runs at midnight @daily Command/Script

@midnight Command/Script

@weekly Runs at midnight on Sunday @weekly Command/Script
@monthly First Day of Each Month @monthly Command/Script
@yearly Runs on Jan 1 at midnight @yearly Command/Script
@reboot Runs after Reboot @reboot Command/Script

How to Create a Cronjob on Ubuntu/Linux

The syntax of creating the cronjob is the same in all the scenarios, i.e., fields for unit time and the last one for command/script. However, the process of accessing the crontab file differs (as the user-specific files and system-wide files are placed at different locations). Let’s dig into both:

Creating a User-Specific Cronjob

The user-specific crontab files are placed inside the directory “/var/spool/cron/crontabs”. Initially, it is empty. To create/edit the crontab file, use the below command (which takes you to your crontab file in edit mode and also creates it if it does not exist):

crontab -e

Here, a cronjob executes the script at the specified location. The script will be executed only at the specified time:

You can write the command in place of the script path. Here are the examples of using the command:

When you save and exit out of the editor, the following prompt appears:

The following other variants can be useful:

  • sudo crontab -e: Opens/Creates the crontab file in edit mode as a root user.
  • crontab -u username -e: Creates/Edits the specific user’s crontab as the mentioned user.

You can view the cronjobs of the current user, as:

crontab -l

Scroll down the output to view the list of cronjobs, as highlighted below. If you see, we have used the “asterisk” character which means this job will run every minute of every hour of every day, and so on.

Creating a System-Wide Cronjob

System-wide cronjobs are applicable irrespective of the users. The system-wide crontab file is located at “/etc/crontab”. This file is edited manually to create a cron job. Let’s see how it works:

Open the file using any editor:

sudo nano /etc/crontab

Here we have defined two cronjobs:

The first job executes the script at a specific time. Whereas the second job runs on the last day of the month at every minute, hour, etc.

Here you can also edit the line “SHELL=/bin/sh” to “SHELL=/bin/bash” to make the bash scripts understandable for the Cronjobs.

Similarly, one can create a cron job based on the special strings. Look at the below cron job which runs every midnight:

Let’s get into further details of creating a crontab.

Predefined Cron Directories | Daily, Hourly, Weekly, and Monthly Jobs

Apart from that, the directory “/etc/” contains the sub-directories for hourly, daily, weekly, and monthly jobs. Let’s list these:

sudo ls /etc/cron.*

You just have to place the executable shell script inside these directories to execute the scripts at the specified time. Moreover, the owner of that script must be the root user.

For instance, the “test.sh” script is created inside the “/etc/cron.daily” directory. Then, it is made executable. Lastly, the ownership is granted to the root user:

sudo touch test.sh #creating a .sh file 
sudo chmod +x test.sh #making it executable 
sudo chown root:root test.sh #changing the ownership to root

Edit the file, place the shebang at the top (to define the type of script), and put some Linux command/script path:

Save and exit. That’s it.

Similarly, you can create the scripts with the same pattern inside any of the directories, i.e., cron.weekly, or cron.monthly to schedule the job for that specific time.

Add the Crontab File in /etc/cron.d to Create a cronjob

This is the least recommended method you just have to put the crontab inside the “/etc/cron.d” directory. The corn service also looks inside the “/etc/cron.d” directory to locate the crontabs and execute the cronjobs inside them.

This directory refers to the root user. Therefore, the file must be created with root as its owner. The “/etc/cron.d/test” file is created with a root user:

The file must define the type of the shell script:

So, the script would run at 17:55Hours on each day of each week.

How to Manage/Configure Cron (Crontab/Cronjob) on Ubuntu/Linux

Managing the cron jobs and crontabs is also an essential activity. Doing so, allows you to manage the cron permissions, cron outputs, cron logs, and much more. The upcoming sections describe the management’s relevant actions:

Allow/Deny Specific Users

The root users can manage the permissions to use the cron. You can allow/deny specific users or all users at once to permit/block them from accessing/using crontabs. The permissions-related cron files are located at “/etc/cron” with the names “/etc/cron.deny” and “/etc/cron.allow”. If any user is blocked, that user won’t be allowed to perform any cron-related activity.

Let’s open the file in the editor:

sudo nano /etc/cron.allow

Enter the username to whom you want to allow/permit the cron activities (use separate lines for multiple users):

Similarly, to block any user, you have to open the file “/etc/cron.deny” and insert the username in it:

sudo nano /etc/cron.deny

Create/Edit the Cronjobs of Other Users

No matter which user is logged in? You can edit/view the cron jobs of any of the users. The syntax of the crontab command in such a case is:

crontab -u <username> -e

Similarly, you can use the sudo to edit the cronjob of the root user.

List the Cronjobs

Once a user-specific job is created, it can be found in the crontab of that user. The crontab command allows you to view the content of the crontab file (where cronjobs are saved) of yourself or any other user. Use one of the below commands as per your requirements:

crontab -l #List the Current User’s Crontab 
crontab -u username -l #List the Crontab of the Mentioned User

sudo crontab -l #Root user’s cronjobs

Remove the Cronjobs

You can remove any of the crontab files using the “-r” flag of the “crontab” command. The command does not show any prompt while deleting. However, you can use the “-i” option to get the confirmation prompt:

$ crontab -r #Delete Without Confirming 
$ crontab -r -i #Delete the Crontab With a Confirmation Prompt

Cron Outputs

By default, the cron outputs are sent at /var/mail/<username>. Whether the cron job results in success or failure, the output is sent to the “/var/mail/username” which is the mailbox of the user associated with the cron job.

Let’s open this file in the terminal (you must put the username correctly)

sudo cat /var/mail/username

Cron Logs

By default, cronlogs are stored at: /var/log/syslog. This file contains the tens of logs/messages of other programs as well. The content of the file is as follows (printed only the recent entries):

Here, you must have to filter the output to view the cron-specific logs. Contrary to that, you can view the cron logs at the cron-specific file or the file of your choice. For that, open the /etc/rsyslog.d/50-default.conf file in any editor and uncomment the “cron.* /var/log/cron.log”. Doing so will direct your logs to the mentioned directory/file.

Bonus: How to Manage Cron (Crontabs and Cronjobs) Using GUI on Ubuntu 22.04

Although, Ubuntu has effective command-line support to deal with cron job/tab. However, you can use the GUI to manage (create, delete) the cronjob/crontab. Ubuntu does not provide any pre-installed GUI utility to manage crontab. However, the snap contains the utility named “mkcron” which is a catalyst in this scenario.

Let’s install it first:

sudo snap install mkcron

Here’s its interface:

  • Where you can configure the parameters.
  • Load the script or write the command to be run.
  • Also, create a cron task by including the parameters/command/script you provided.

The cron task will run automatically at the specific scheduled time.

That’s all about the crontab, from basic to advanced.

Bottom Line

You might set a reminder to run the command at 16:44 hours tomorrow. Don’t worry, Ubuntu/Linux has crontab/cronjobs for you. You can create cronjobs at any time inside the specific crontab. Now, the command would be executed at that time.

The crontab/cronjobs are usually preferred and used on the server side where the system has to run for numerous days/months in a single go. By doing so, an administrator can automate the routine maintenance tasks.

Well, we have covered all the aspects of crontab/cronjob that apply to both normal Ubuntu systems/servers.

Print Friendly, PDF & Email
Categories