mysqlbackup.sh 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. #!/bin/bash
  2. # Simple script to backup MySQL databases
  3. # Parent backup directory
  4. backup_parent_dir="/var/backups/mysql"
  5. # MySQL settings
  6. mysql_user="root"
  7. mysql_password="ROOTPASSWD"
  8. # Read MySQL password from stdin if empty
  9. # if [ -z "${mysql_password}" ]; then
  10. # echo -n "Enter MySQL ${mysql_user} password: "
  11. # read -s mysql_password
  12. # echo
  13. # fi
  14. # Check MySQL password
  15. echo exit | mysql --user=${mysql_user} --password=${mysql_password} -B 2>/dev/null
  16. if [ "$?" -gt 0 ]; then
  17. echo "MySQL ${mysql_user} password incorrect"
  18. exit 1
  19. else
  20. echo "MySQL ${mysql_user} password correct."
  21. fi
  22. # TODO rotate backups
  23. # Create backup directory and set permissions
  24. backup_date=`date +%Y_%m_%d_%H_%M`
  25. backup_dir="${backup_parent_dir}/${backup_date}"
  26. echo "Backup directory: ${backup_dir}"
  27. mkdir -p "${backup_dir}"
  28. chmod 700 "${backup_dir}"
  29. # Get MySQL databases
  30. mysql_databases=`echo 'show databases' | mysql --user=${mysql_user} --password=${mysql_password} -B | sed /^Database$/d`
  31. # Backup and compress each database
  32. for database in $mysql_databases
  33. do
  34. if [ "${database}" == "information_schema" ] || [ "${database}" == "performance_schema" ]; then
  35. additional_mysqldump_params="--skip-lock-tables"
  36. else
  37. additional_mysqldump_params=""
  38. fi
  39. echo "Creating backup of \"${database}\" database"
  40. mysqldump ${additional_mysqldump_params} --user=${mysql_user} --password=${mysql_password} ${database} | gzip > "${backup_dir}/${database}.gz"
  41. chmod 600 "${backup_dir}/${database}.gz"
  42. done