Skip to content

Instantly share code, notes, and snippets.

@mobeigi
Created Jul 3, 2020
Embed
What would you like to do?
Linux Server Backup Script for Files + MySQL Databases
#!/usr/bin/env bash
# Server Backup Script
# Backs up:
# MySQL databases
# Important files on file system
# Variables
TIMESTAMP=$(date +"%d-%m-%Y_%H-%M-%S")
BACKUP_DIR="/root/backups/full"
FILE_BACKUP_FILE_NAME="backups-file-backup-$TIMESTAMP"
MYSQL_BACKUP_FILE_NAME="backups-mysql-backup-$TIMESTAMP"
MYSQL_USER="root"
MYSQL=/usr/bin/mysql
MYSQL_PASSWORD="example_pass"
MYSQLDUMP=/usr/bin/mysqldump
cd $BACKUP_DIR
# Backup MySQL databases
echo "Backing up MYSQL databases..."
databases=`$MYSQL --user=$MYSQL_USER -p$MYSQL_PASSWORD -e "SHOW DATABASES;" | grep -Ev "(Database|information_schema|performance_schema)"`
for db in $databases; do
$MYSQLDUMP --force --opt --user=$MYSQL_USER -p$MYSQL_PASSWORD --databases $db > "$db.sql"
done
tar --remove-files -czvf "$MYSQL_BACKUP_FILE_NAME.tar.gz" *.sql
# Backup files
echo "Backing up files..."
tar --exclude=$BACKUP_DIR -zcvf "$FILE_BACKUP_FILE_NAME.tar.gz" \
"/etc" \
"/home" \
"/usr/local/etc" \
"/usr/local/src" \
"/opt" \
"/srv" \
"/root" \
"/var/spool/mail" \
"/var/www" \
"/var/log"
echo "Backup complete."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment