Advertisements

How to Use Cron Jobs

  • Post last modified:October 20, 2023
  • Post category:Linux
  • Post comments:0 Comments
  • Reading time:4 mins read

In this post, we will explore how to automate tasks with cron jobs and shell scripting.

Table of Contents:

Step 1: Create a shell script

Advertisements

The first step is to create a shell script that performs the task you want to automate. For example, let’s say you want to back up a directory called /var/www/html every day at 3:00 AM. You can create a shell script called backup.sh that uses the tar command to create a compressed backup of the directory.

#!/bin/bash
# Backup script for /var/www/html directory
tar -czvf /backup/html_backup_$(date +\%Y-\%m-\%d).tar.gz /var/www/html

In this script, we are using the tar command to create a compressed backup of the /var/www/html directory. We are also using the date command to append the current date to the filename of the backup.

Step 2: Make the script executable

The next step is to make the script executable:

chmod +x backup.sh

Step 3: Test the script

Before we can automate the script, we need to test it to make sure it works as expected. You can do this by running the script manually and verifying that it creates a backup file in the /backup directory.

./backup.sh

This command executes the backup.sh script and creates a backup file in the /backup directory.

Step 4: Create a cron job

The final step is to create a cron job that runs the backup.sh script on a regular basis. You can do this by editing the crontab file.

crontab -e

You can then add the following line to schedule the backup.sh script to run every day at 3:00 AM.

0 3 * * * /path/to/backup.sh

Advertisements

This cron job will execute the backup.sh script every day at 3:00 AM.

you can use this online tool to generate a schedule.

Leave a Reply