| | 1 | This script dumps MySQL databases with a directory per database and a file per table. |
| | 2 | |
| | 3 | {{{ |
| | 4 | #!/bin/bash |
| | 5 | |
| | 6 | # dump databases with a file per table |
| | 7 | |
| | 8 | # this script is based on |
| | 9 | # https://stackoverflow.com/questions/3669121/dump-all-mysql-tables-into-separate-files-automagically |
| | 10 | |
| | 11 | # check that the script is being run by root |
| | 12 | if [[ "$(id -u)" != "0" ]] ; then |
| | 13 | echo "You must run $0 as root or via sudo" |
| | 14 | exit 2 |
| | 15 | fi |
| | 16 | |
| | 17 | # Check that /root/.my.cnf exists |
| | 18 | test -f /root/.my.cnf || echo "This script needs a /root/.my.cnf" |
| | 19 | # /root/.my.cnf format: |
| | 20 | # [client] |
| | 21 | # user = root |
| | 22 | # password = PASSWORD |
| | 23 | # host = localhost |
| | 24 | |
| | 25 | |
| | 26 | # list of databases, omitting the system databases |
| | 27 | DATABASES=$(mysql -NBA -e 'show databases' | grep -v 'mysql' | grep -v 'information_schema' | grep -v 'performance_schema') |
| | 28 | # backup base directory |
| | 29 | BASE_DIR="/var/backups/mysql/databases" |
| | 30 | |
| | 31 | # check $BASE_DIR exists |
| | 32 | test -d ${BASE_DIR} || mkdir -p ${BASE_DIR} || exit 1 |
| | 33 | |
| | 34 | for d in ${DATABASES} ; do |
| | 35 | # make a directory for each database it |
| | 36 | test -d ${BASE_DIR}/${d} || mkdir -p ${BASE_DIR}/${d} || exit 1 |
| | 37 | echo "Backing up database ${d} to ${BASE_DIR}/${d}" |
| | 38 | # set a counter to zero |
| | 39 | tbl_count="0" |
| | 40 | # get a list of the database tables |
| | 41 | TABLES=$(mysql -NBA -D ${d} -e 'show tables') |
| | 42 | for t in ${TABLES} |
| | 43 | do |
| | 44 | echo "Dumping table: ${t}" |
| | 45 | mysqldump ${d} ${t} > ${BASE_DIR}/${d}/${t}.sql || exit 1 |
| | 46 | ( tbl_count++ ) |
| | 47 | done |
| | 48 | echo "${tbl_count} tables dumped from database ${d} into ${BASE_DIR}/${d}" |
| | 49 | done |
| | 50 | |
| | 51 | echo "Databases backup successful" |
| | 52 | exit 1 |
| | 53 | }}} |