useful scripts

Backup MySQL

#!/bin/bash

# Load .env file from MY_APP folder
ENV_FILE="/var/www/html/MY_APP/.env"

if [ ! -f "$ENV_FILE" ]; then
    echo "The .env was not found on $(dirname "$0")"
    exit 1
fi

# Read .env
source "$ENV_FILE"

# Check if the necessary vars are defined
if [ -z "$DB_DATABASE" ] || [ -z "$DB_USERNAME" ] || [ -z "$DB_PASSWORD" ]; then
    echo "Error: Variable DB_DATABASE, DB_USERNAME or DB_PASSWORD not defined on .env"
    exit 1
fi

# Backup config
BACKUP_DIR="/home/dev/backups"
DATE=$(date +%Y%m%d_%H%M%S)
BACKUP_FILE="$BACKUP_DIR/backup_$DB_DATABASE_$DATE.sql"
ZIP_FILE="$BACKUP_DIR/backup_$DB_DATABASE_$DATE.zip"
MAX_BACKUPS=10

# Create folder if it does not exist
mkdir -p "$BACKUP_DIR"

# Dump data on the backup file
mysqldump -u "$DB_USERNAME" -p"$DB_PASSWORD" "$DB_DATABASE" > "$BACKUP_FILE"

# Check if the backup file was created
if [ $? -eq 0 ]; then
    echo "Backup of $DB_DATABASE created on: $BACKUP_FILE"
    
    echo "Zipping the .sql file..."
    zip "$ZIP_FILE" "$BACKUP_FILE"
    
    echo "Removing temporary file..."
    rm "$BACKUP_FILE"
    
    echo "Keeping only the last $MAX_BACKUPS..."
    ls -t "$BACKUP_DIR"/backup_$DB_DATABASE_*.zip | tail -n +$((MAX_BACKUPS + 1)) | xargs -I {} rm {}
else
    echo "Error on creating a security copy of $DB_DATABASE database!"
    exit 1
fi

Monitor open file descriptions

Last updated

Was this helpful?