Skip to content

Instantly share code, notes, and snippets.

@danieleambrosino
Created May 23, 2023 08:12
Show Gist options
  • Save danieleambrosino/2a66549b2a9b0e577f0226ab43369312 to your computer and use it in GitHub Desktop.
Save danieleambrosino/2a66549b2a9b0e577f0226ab43369312 to your computer and use it in GitHub Desktop.
Simple bash script to backup a SQLite database
#!/bin/bash
# Check if source database and destination directory are provided as command line parameters
if [ $# -ne 2 ]; then
echo "Usage: $0 <source_database> <destination_directory>"
exit 1
fi
# Get the source database and destination directory from command line parameters
source_db="$1"
destination_dir="$2"
# Check if the source database exists
if [ ! -f "$source_db" ]; then
echo "Source database not found: $source_db"
exit 1
fi
# Check if the destination directory exists
if [ ! -d "$destination_dir" ]; then
echo "Destination directory not found: $destination_dir"
exit 1
fi
# Create a temporary file to store the backup
tmp_backup_file=$(mktemp)
# Generate the backup in the temporary file
sqlite3 "$source_db" ".backup '$tmp_backup_file'"
# Calculate the hash of the backup file
backup_hash=$(md5sum "$tmp_backup_file" | awk '{print $1}')
function move_backup() {
local backup_file="$destination_dir/backup_$(date --iso-8601).sqlite3"
mv "$tmp_backup_file" "$backup_file"
# Restrict database file permissions
chmod 400 $backup_file
echo "Backup created: $backup_file"
}
# Calculate the hash of the last backup file in the destination directory
last_backup_file=$(ls -t "$destination_dir" | head -n1)
if [ -z "$last_backup_file" ]; then
move_backup
exit 0
fi
last_backup_hash=$(md5sum "$destination_dir/$last_backup_file" | awk '{print $1}')
# Compare the hashes and move the backup to the destination directory if they are different
if [ "$last_backup_hash" != "$backup_hash" ]; then
move_backup
else
rm -f "$tmp_backup_file"
echo "No changes detected with $last_backup_file - skipping backup."
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment