BASH
Automate Daily Database Backups (MySQL Example)
Safeguard your data with a bash script that performs daily MySQL database backups, compresses them, and timestamps the archives for easy recovery.
#!/bin/bash
DB_USER="your_db_user"
DB_PASS="your_db_password"
DB_NAME="your_database_name"
BACKUP_DIR="/var/backups/mysql"
RETENTION_DAYS=7 # Number of days to keep backups
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
BACKUP_FILE="$BACKUP_DIR/$DB_NAME-$TIMESTAMP.sql.gz"
# Create backup directory if it doesn't exist
mkdir -p "$BACKUP_DIR"
echo "Starting backup of database '$DB_NAME' to $BACKUP_FILE..."
# Perform the MySQL dump and compress it
mysqldump -u "$DB_USER" -p"$DB_PASS" "$DB_NAME" | gzip > "$BACKUP_FILE"
if [ $? -eq 0 ]; then
echo "Database backup successful!"
else
echo "Error: Database backup failed!"
rm -f "$BACKUP_FILE" # Clean up failed backup file
exit 1
}
# Clean up old backups
echo "Cleaning up old backups older than $RETENTION_DAYS days..."
find "$BACKUP_DIR" -type f -name "*.sql.gz" -mtime +"$RETENTION_DAYS" -delete
echo "Backup process complete."
How it works: This script automates the process of creating daily backups for a MySQL database. It uses `mysqldump` to export the database content, pipes the output to `gzip` for compression, and saves it to a specified `BACKUP_DIR` with a timestamped filename. It also includes logic to clean up old backups, keeping only those within the `RETENTION_DAYS` period. This helps manage disk space and ensures you always have recent database snapshots. Remember to replace `DB_USER`, `DB_PASS`, `DB_NAME`, and `BACKUP_DIR` with your actual database credentials and desired backup location. For PostgreSQL, you would use `pg_dump` instead of `mysqldump`.