How to Automate Linux Backups with a Simple Bash Script
Bash Automated Backup Integrity means a bash script makes backups by itself, and it also checks that the backup file is still healthy and not broken. A bash automated backup is commonly a simple script that collects important folders, compresses them into one file, and can be scheduled to run every day without manual work.
A backup is only useful if it can be restored later, so checking integrity helps you avoid a backup that exists but cannot be used.
Also, many backup scripts clean old backups to save disk space, so the server does not fill up over time.
In this guide, you will learn to write a bash script that not only backs up your files automatically but also verifies their integrity to ensure your backups are actually usable when you need them.
By the end of this guide, you will have a script that:
- Compresses specific directories into a .tar.gz archive.
- Timestamps every backup file for easy organization.
- Verifies the integrity of the backup immediately after creation.
- Generates a Checksum (SHA256) for future validation.
- Rotates Backups by automatically deleting files older than 7 days to save disk space.
- Logs every step to a file for monitoring.
For a stable environment to run automated backups and scheduled tasks, a reliable VPS is important. You can check PerLod Hosting to explore the flexible VPS server plans.
Table of Contents
Prerequisites for a Bash Automated Backup Integrity Script
Before running a Bash Automated Backup Integrity script, make sure these basics are ready:
A Linux system such as Ubuntu, CentOS, Debian, and RHEL: The script is designed for Linux environments, where common tools like the shell and standard backup commands are available.
Basic familiarity with the terminal: You should know how to open a terminal, move between directories, edit a file, and run commands.
Root or sudo privileges: Backups often need access to system folders like /etc and service files, so you must have permission to read those files and write backup files to your backup location.
Note: For projects that need lots of disk space, mainly for storing backup archives, PerLod has High Storage VPS options that are designed for backups and large files.
Step 1. Prepare the Backup Folders
You must create a directory for your scripts and a directory for storing backups, which makes troubleshooting and permissions simpler.
Create a directory for your scripts with the command below:
mkdir -p /root/scripts
Create a directory where backups will be stored by using this command:
mkdir -p /backups/server-files
Step 2. Write a Bash Backup Script With Logging, Integrity Check, and Cleanup
In this step from Bash Automated Backup Integrity, you can create the bash automated backup file and build the script in small parts, so it’s easy to read and change later.
Create a new file named auto_backup.sh with your desired text editor:
nano /root/scripts/auto_backup.sh
You can easily define variables or configuration, which control what gets backed up, where backups are stored, how long to keep them, and where logs go. Add the following variables to the file:
#!/bin/bash
# Configuration
SOURCE_DIRS="/var/www/html /etc/nginx" # Directories to back up
BACKUP_ROOT="/backups/server-files" # Where to store backups
RETENTION_DAYS=7 # How many days to keep backups
DATE_STAMP=$(date +%Y-%m-%d_%H-%M-%S) # Current date and time
BACKUP_FILE="backup_$DATE_STAMP.tar.gz" # The final filename
LOG_FILE="/var/log/backup_script.log" # Log file location
Then, add a logging function to the file, which helps track success and failure, and it makes troubleshooting easier later:
# Function to log messages with timestamps
log_message() {
echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" | tee -a "$LOG_FILE"
}
log_message "Starting backup process..."
Now you can create the archive with tar, where the actual backup file is created:
# Create the compressed archive
log_message "Compressing files from: $SOURCE_DIRS"
tar -czpf "$BACKUP_ROOT/$BACKUP_FILE" $SOURCE_DIRS 2>> "$LOG_FILE"
# Check if the tar command was successful
if [ $? -eq 0 ]; then
log_message "Backup archive created successfully: $BACKUP_FILE"
else
log_message "CRITICAL ERROR: Backup creation failed!"
exit 1
fi
Next, add the verification of integrity with create checksum. This part checks if the archive can be read, and then creates a SHA-256 checksum you can use later to confirm the file was not corrupted or changed.
Listing an archive tar -t is a common integrity check method.
For checksum verification, Linux provides sha256sum, and it supports -c to check files later against a saved checksum file.
# Verify the integrity of the archive
log_message "Verifying backup integrity..."
# 'tar -tzf' lists contents; we redirect output to /dev/null to keep it silent
if tar -tzf "$BACKUP_ROOT/$BACKUP_FILE" > /dev/null 2>&1; then
log_message "Integrity Check: PASSED. Archive is valid."
# Generate SHA256 Checksum for future verification
sha256sum "$BACKUP_ROOT/$BACKUP_FILE" > "$BACKUP_ROOT/$BACKUP_FILE.sha256"
log_message "Checksum generated."
else
log_message "Integrity Check: FAILED. The archive is corrupt."
exit 1
fi
Finally, add the retention policy, which automatically deletes old backup files so storage does not fill up over time:
# Delete backups older than 7 days
log_message "Cleaning up old backups (older than $RETENTION_DAYS days)..."
find "$BACKUP_ROOT" -name "backup_*.tar.gz*" -mtime +$RETENTION_DAYS -delete
log_message "Backup process finished successfully."
At this point, you can put everything together into a clean and ready-to-run Bash script. Paste the following full code into your automated bash file:
#!/bin/bash
# =========================================================
# AUTOMATED BACKUP SCRIPT WITH INTEGRITY CHECK
# =========================================================
# --- Configuration ---
SOURCE_DIRS="/var/www/html /etc/nginx" # Add your directories here
BACKUP_ROOT="/backups/server-files"
RETENTION_DAYS=7
DATE_STAMP=$(date +%Y-%m-%d_%H-%M-%S)
BACKUP_FILE="backup_$DATE_STAMP.tar.gz"
LOG_FILE="/var/log/backup_script.log"
# --- Logging Function ---
log_message() {
echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" | tee -a "$LOG_FILE"
}
# --- 1. Pre-Flight Checks ---
mkdir -p "$BACKUP_ROOT"
log_message "=== Backup Started ==="
# --- 2. Create Backup ---
log_message "Archiving directories: $SOURCE_DIRS"
tar -czpf "$BACKUP_ROOT/$BACKUP_FILE" $SOURCE_DIRS 2>> "$LOG_FILE"
if [ $? -ne 0 ]; then
log_message "ERROR: Tar command failed. Backup aborted."
exit 1
fi
log_message "Archive created: $BACKUP_FILE"
# --- 3. Integrity Check ---
log_message "Running health check on archive..."
if tar -tzf "$BACKUP_ROOT/$BACKUP_FILE" > /dev/null 2>&1; then
log_message "SUCCESS: Archive integrity verified."
# Generate Hash
sha256sum "$BACKUP_ROOT/$BACKUP_FILE" > "$BACKUP_ROOT/$BACKUP_FILE.sha256"
else
log_message "FAILURE: Archive is corrupt! Do not rely on this backup."
exit 1
fi
# --- 4. Cleanup Old Backups ---
log_message "Removing backups older than $RETENTION_DAYS days..."
find "$BACKUP_ROOT" -name "backup_*.tar.gz*" -type f -mtime +$RETENTION_DAYS -delete
log_message "=== Backup Completed Successfully ==="
echo "-------------------------------------" >> "$LOG_FILE"
Once you are done, make the script file executable with the command below:
chmod +x /root/scripts/auto_backup.sh
To confirm your bash script is working correctly, you can run it manually with the command below:
/root/scripts/auto_backup.sh
Or, you can use the command below inside the scripts folder:
./auto_backup.sh
After running it, check the log file to see the results:
cat /var/log/backup_script.log
You should see messages like “Backup archive created successfully” and “Integrity Check: PASSED“.
Step 3. Automate the Backup Script with Cron
After your backup script is configured, the next step is to schedule it so it runs automatically every day. To do this, you can use Cron, which is the standard Linux scheduler used to run commands at set times.
Open the crontab editor with the command below:
crontab -e
This opens your user’s cron schedule file, where you can add timed jobs.
For example, you can add the daily 3:00 AM job by adding this line at the end of the file:
0 3 * * * /root/scripts/auto_backup.sh
Once you are done, save and close the file.
Step 4. Restore Backup File: Test the Recovery Process
Testing a restore means extracting your .tar.gz backup file and checking that the files come back correctly. The tar command is commonly used to extract .tar.gz archives on Linux, and -C can extract into a chosen folder instead of the current one.
Run the command below in the folder where your backup file exists:
tar -xzhf backup_2023-10-27_03-00-00.tar.gz
This extracts the backup contents into your current working directory.
If you want to extract to a specific folder, you must create a test folder and then extract into it:
mkdir -p /tmp/restore_test
tar -xzhf backup_filename.tar.gz -C /tmp/restore_test
FAQs
Is sha256sum better than md5sum for checking backups?
Yes. While md5sum is faster, it is older and less secure. sha256sum is the modern standard because it is much harder to trick.
What happens if tar -tzf finds an error?
If tar -tzf fails, it means your backup file is corrupted and unusable. The script logs this as a “FAILURE.” If you see this error, you should immediately check your disk space and file permissions.
Can I recover files from a corrupted .tar.gz file?
If the file is only partially damaged, you might be able to extract some files using tar with the –ignore-failed-read option or by using recovery tools like gzrecover. However, a corrupted archive is unreliable, which is why the integrity check in this script is so important; it warns you before you need to restore.
Conclusion
At this point, you have a strong backup system that can run on its own with a schedule. It saves disk space by compressing your backup into a single archive file, and it improves trust by checking the archive right after it is created. This setup also keeps your server clean by removing old backup files automatically, so your storage does not slowly fill up.
Important Note: Always remember that a backup that is not tested may fail when you really need it, so run the script once manually and make sure it completes without errors.
We hope you enjoy this guide on Bash Automated Backup Integrity. Subscribe to our X and Facebook channels to get the latest updates and articles.
For further reading: