MySQL Backup Utility

Public

A script that backup mysql database using `mysqldump` utility.

</> CopyGet raw version
bash
  1. #!/bin/bash
  2. #
  3. # Copyright 2013 Gerald Villorente <gerald@ninjas-corner.com>
  4. #
  5. # This program is free software; you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation; either version 2 of the License, or
  8. # (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program; if not, write to the Free Software
  17. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  18. # MA 02110-1301, USA.
  19. #
  20. # A script that backup mysql database using `mysqldump` utility.
  21. #
  22. # How to use:
  23. # Make sure that the this script is executable. If not then you just need to
  24. # add execute permission by doing this "chmod +x dumpDb.sh".
  25. # Run the script as normal user and supply the database name(s) as parameter.
  26. # Ex: ./dumpDb.sh mydatabasename1 mydatabasename2 mydatabasename3
  27. #
  28. # For security.
  29. # Place your mysql creds somewhere else (txt file).
  30. #
  31. # TODO:
  32. # 1. Support multiple database backup. (Done)
  33. # 2. Support remote backup over SSH tunnel.
  34. # 3. Support by-date backup. This is useful when doing daily backup and not
  35. # overwrite the existing file. (Done)
  36. #
  37. # What this script does?
  38. # Backup database in a specified directory in a compressed format. This script
  39. # also support multiple database backup per execution.
  40. #
  41. # Initialize the target directory.
  42. HOMEDIR=$( getent passwd "$USER" | cut -d: -f6 )
  43. TARGETDIR="SQLBackups"
  44. BACKUPDIRECTORY=$HOMEDIR/$TARGETDIR
  45. if [ ! -d "$BACKUPDIRECTORY" ]; then
  46. mkdir $BACKUPDIRECTORY
  47. fi
  48. DBUSER=$(sudo cat /var/secret/key | grep 'DBUSER' | cut -c8-)
  49. DBPASS=$(sudo cat /var/secret/key | grep 'DBPASS' | cut -c8-)
  50. DBHOST=$(sudo cat /var/secret/key | grep 'DBHOST' | cut -c8-)
  51. #
  52. # Notify the user.
  53. echo "Running mysqldump utility..."
  54. echo ""
  55. #
  56. # Dump the database(s).
  57. for databasename in "$@"
  58. do
  59. mysqldump -h$DBHOST -u$DBUSER -p$DBPASS $databasename | gzip > $BACKUPDIRECTORY/$databasename-`date +%d-%m-%y`.sql.gz
  60. done
  61. #
  62. # Notify that the dump is done.
  63. echo "Backup done."