Automated Backup Script with Cron Job

Prepared by: Anwer Sadath Abdul Muttaliff

Objective

This project demonstrates how to create a Bash script that automatically backs up the /var/www/html/index.html file daily and stores the backup in /tmp/backup_html/. The script is scheduled using cron to run without manual intervention.

Step 1: Create the Backup Script

Write the Backup Script

Create a script named backup.sh:

#!/bin/bash

# Define backup directory
BACKUP_DIR="/tmp/backup_html"

# Create backup directory if it doesn't exist
mkdir -p $BACKUP_DIR

# Create a backup archive of index.html
tar -czf $BACKUP_DIR/backup_html.tar.gz /var/www/html/index.html
Backup Script
Make the Script Executable
$ chmod +x /home/anwer/backup.sh

Step 2: Schedule the Script Using Cron Job

Edit the Crontab

Open the crontab editor and add the following line to schedule the script to run daily at 11:43 AM:

43 11 * * * /home/anwer/backup.sh
Cron Job List

Troubleshooting the Cron Job Issue

Issue: Cron Job Fails to Execute

The cron job failed to execute because the script contained the sudo command, which requires a password. The solution was to remove sudo from the script and configure passwordless execution for the tar command in the sudoers file.

Cron Logs
Final Fix: Remove sudo from the Script

Edit the script to remove sudo:

#!/bin/bash

# Define backup directory
BACKUP_DIR="/tmp/backup_html"

# Create backup directory if it doesn't exist
mkdir -p $BACKUP_DIR

# Create a backup archive of index.html
tar -czf $BACKUP_DIR/backup_html.tar.gz /var/www/html/index.html
Edit Sudoers File

Final Outcome

The cron job now runs successfully at 11:43 every day, creating a backup file in /tmp/backup_html/backup_html.tar.gz without requiring a password.

Cron Job Working

Key Takeaways

Back to Top Back to Home