Create cronjob script using crontab

Cronjob are the tasks which we want to run on a regular internal on a Linux machine. For example we can copy certain file in every 5 min from one directory to another directory or we can check if certain ip address was reachable from the system. We can schedule a cronjob using crontab which can use script or commands, the commands/scipt mentioned will run as per the schedule mentioned in the crontab. In this post we will see sample script example for crontab.

There is a certain format we need to follow to schedule a cronjob. We need to specify which command/script we need to run at what time, what date it need to be run.

Syntax for crontab to schedule cronjob:

Crontab useful command

Sample script for scheduling cronjob using crontab

Lets understand crontab command in detail with an example. For this example we have used Ubuntu 18.04 version. We have created a script which can ping to a destination and stored the ping command output to a file.

Step 1 > Create a script file named as at /localdisk directory, content of the file is as following, the script say ping the ip address “” 5 time and save the output to ping.txt file:

ping -c 5 > ping.txt

Step 2 > Change the file permission to make it a executable file :

chmod +x

Step 3 > Take a backup of current cronjob: The current cronjob will be saved in a new file named as currentcron

crontab -l > currentcron

Step 4> Create a copy of the file : We will create a copy of current cronjob and save them in a new file named newcron. The file currentcron can be used to restore to previous cronjob tasks.

cp currentcron newcron

Step 5 > Append new cron job to the copied file. Either we can edit the newcron file using file editor or we can use echo command to append the text to the end of the file. This cron job will run in every 2 minute(*/2)

echo "*/2 * * * * /localdisk/" >> newcron

Step 6 > Update the cron job with new task :

crontab newcron


Check current cron jobs using below command :

crontab -l

Content/output of the cronjob will be in home folder of the user who have scheduled the cronjob.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.