Weekly Backup Script

This article explains how to create a Bash script for performing weekly backups of a folder to an external SMB share, naming the backups with the date, and ensuring that old files are not overwritten.

Create the Backup Script

Prerequisites

Before setting up the backup script, ensure you have the following:

Create the Backup Script

You can create a Bash script for this purpose. Save the following code in a file, e.g., weekly_backup.sh:

#!/bin/bash

# Source directory to be backed up
source_dir="/path/to/source_directory"

# SMB share URL where you want to store the backups
smb_share="smb://username@hostname/share_name"

# Destination directory on the SMB share
smb_dir="/path/to/smb/directory"

# Define a timestamp for the current date
timestamp=$(date "+%Y%m%d")

# Set the backup directory name with the timestamp
backup_dir="${smb_dir}/backup_${timestamp}"

# Check if the destination directory exists, and create it if not
if ! smbclient -L "${smb_share}" -U username%password >/dev/null 2>&1; then
    echo "Error: Unable to access the SMB share. Please check the SMB share URL, username, and password."
    exit 1
fi

# Perform the backup using rsync
rsync -avz --no-links --exclude-from=/path/to/exclude_list.txt "$source_dir" "$backup_dir"

# Check if the rsync command was successful
if [ $? -eq 0 ]; then
    echo "Backup completed successfully."
else
    echo "Backup failed."
    exit 1
fi

exit 0

Replace the placeholders in the script with your actual values:

Make the script executable with the following command:

chmod +x weekly_backup.sh

Schedule the Script

To run the script automatically on a weekly basis, use a scheduling tool like cron. Edit your crontab using the crontab -e command and add a line like this to run the script every Sunday at midnight:

0 0 * * 0 /path/to/weekly_backup.sh

This schedules the script to run every Sunday at midnight, creating a new backup directory with a timestamp to avoid overwriting old backups.

Now, you have a weekly backup script in place to safeguard your data on an SMB share.