Skip to content

Instantly share code, notes, and snippets.

@ripsnortntear
Created March 31, 2025 06:18
Show Gist options
  • Save ripsnortntear/8fc0b116647af1419ad9a96c8696d9c0 to your computer and use it in GitHub Desktop.
Save ripsnortntear/8fc0b116647af1419ad9a96c8696d9c0 to your computer and use it in GitHub Desktop.
This Bash script is designed for creating and restoring backups of specified directories on a Unix-like system.
#!/bin/bash
# Define backup and restore directories
BACKUP_DIR="/mnt/storage" # Change this to your desired backup location
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
MAX_SIZE=250M # Maximum size of each archive part (250 MB)
DIRECTORIES=(
"/etc"
"/var"
"/home"
"/usr/local"
"/opt"
"/srv"
"/root"
"/boot"
)
# Function to create a backup
backup() {
echo "Starting backup..."
# Ensure the backup directory exists
mkdir -p "$BACKUP_DIR"
# Check if all directories exist
for dir in "${DIRECTORIES[@]}"; do
if [[ ! -d "$dir" ]]; then
echo "Warning: Directory $dir does not exist. Skipping."
fi
done
# Create the backup using 7z and split into parts
BACKUP_FILE="$BACKUP_DIR/backup_$TIMESTAMP.7z"
if 7z a -v"$MAX_SIZE" "$BACKUP_FILE" "${DIRECTORIES[@]}"; then
echo "Backup completed successfully. Created files:"
ls -lh "$BACKUP_DIR/backup_$TIMESTAMP.*"
else
echo "Error occurred during backup."
exit 1
fi
}
# Function to restore from backup
restore() {
local backup_prefix="$1"
# Check if the backup prefix is provided
if [[ -z "$backup_prefix" ]]; then
echo "Error: Backup prefix not specified."
exit 1
fi
echo "Starting restore from $backup_prefix..."
# Check if the backup files exist
if ls "$backup_prefix.*" 1> /dev/null 2>&1; then
if 7z x "$backup_prefix.*" -o/; then
echo "Restore completed successfully."
else
echo "Error occurred during restore."
exit 1
fi
else
echo "Error: No backup files found with prefix '$backup_prefix'."
exit 1
fi
}
# Main script logic
case "$1" in
backup)
backup
;;
restore)
restore "$2"
;;
*)
echo "Usage: $0 {backup|restore <backup_file_prefix>}"
exit 1
;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment