Skip to main content

Script - Backup Script for Home Directories and MySQL Databases

#!/bin/sh

# Home directory to backup must be absolute path, with trailing slash 
home_dir='/home/' 
# Target backup directory, must be absolute path, with trailing slash 
backup_dir='/backups/'

# Database user 
db_user='root' 
# Database Password 
db_pwd=''

cd "$home_dir" 
# Get list of users based on home dir 
users=`find . -maxdepth 1 -type d \( -iname "*" ! -iname "backups" ! -iname "lost+found" \) -exec echo {} \; | sed "s#./##" | grep -v '^/home$'`
for user in $users; do 
    # Skip if user string is empty 
    if [ $user == "" -o $user == ".." -o $user == "." ]; then 
        continue 
    fi 
    # Archive all files in directory 
    archive="$backup_dir`date +%Y%m%d`.$user.tar.gz" 
    tar czf "$archive" "$user" 
done

# Database backup script 
if [ ! -z "$db_pwd" ]; then 
    databases=`mysql -u$db_user -p$db_pwd -e "SHOW DATABASES;" | tr -d "| " | grep -v Database` 
else
    databases=`mysql -u$db_user -e "SHOW DATABASES;" | tr -d "| " | grep -v Database` 
fi 
cd $backup_dir 
for db in $databases; do 
    if [[ "$db" != "information_schema" ]] && [[ "$db" != "performance_schema" ]] && [[ "$db" != "mysql" ]] && [[ "$db" != _* ]] ; then 
        sql="`date +%Y%m%d`.$db.sql" 
        echo "Dumping database: $db" 
        if [ -z "$db_pwd" ]; then 
            mysqldump -u$db_user $db > $sql 
        else 
            mysqldump -u$db_user -p$db_pwd $db > $sql 
        fi 
        tar -czf "`date +%Y%m%d`.$db.sql.tar.gz" $sql 
        rm $sql 
    fi 
done

NOTE: Add this to cronjob to delete backups older than 90 days: find . -type d -mtime +90 -exec rm {}\;