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='/home/tingwai/Works/scripts/serverBackup/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 -exec echo {} \; | sed "s#./##"`
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=`/opt/lampp/bin/mysql -u$db_user -p$db_pwd -e "SHOW DATABASES;" | tr -d "| " | grep -v Database`
else
 databases=`/opt/lampp/bin/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
 /opt/lampp/bin/mysqldump -u$db_user $db > $sql
 else
 /opt/lampp/bin/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