Last active
March 28, 2024 15:36
-
-
Save martipoe/413abaea776d78f9214489d8071883b7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/bash | |
| set -eu | |
| # usage: ./mariadb_backup.sh BACKUP_DIRECTORY DATABASE TAG KEEP_DUMPS | |
| # This script creates compressed mariadb dumps, adds a tag to the file name and retains a specified number of these dumps. | |
| # Tags allow using the same script for various retention schedules. | |
| # Warning: Retention is not based on file age, but file number. | |
| # Example crontab: | |
| # 0 */6 * * * /bin/bash <path>/mariadb_backup.sh /data/mariadb_backup/ db_test hourly 4 | |
| # @daily /bin/bash <path>/mariadb_backup.sh /data/mariadb_backup/ db_test daily 7 | |
| # @weekly /bin/bash <path>/mariadb_backup.sh /data/mariadb_backup/ db_test weekly 4 | |
| # @monthly /bin/bash <path>/mariadb_backup.sh /data/mariadb_backup/ db_test monthly 3 | |
| BACKUP_DIRECTORY="$1" | |
| DUMP_DATABASE="$2" | |
| TAG="$3" | |
| KEEP_DUMPS="$4" | |
| DUMP_OPTIONS="--single-transaction --skip-lock-tables --skip-extended-insert --add-drop-database --order-by-primary" | |
| # PERFORM SOME CHECKS | |
| if [ ! -d "${BACKUP_DIRECTORY}" ]; then | |
| echo "Backup directory does not exist: ${BACKUP_DIRECTORY}" | |
| exit 1 | |
| fi | |
| if ! /usr/bin/mysql -Bse "show databases" | grep -q "${DUMP_DATABASE}"; then | |
| echo "Database is not accessible: ${DUMP_DATABASE}" | |
| exit 1 | |
| fi | |
| # CREATE BACKUP | |
| NOW=$(date '+%Y-%m-%d_%H-%M') | |
| MARIADB_DUMP=$(/usr/bin/mariadb-dump ${DUMP_OPTIONS} --databases "${DUMP_DATABASE}" > gzip > "${BACKUP_DIRECTORY}/${DUMP_DATABASE}.${TAG}.${NOW}.sql.gz") | |
| # REMOVE EXPIRED BACKUPS | |
| find "${BACKUP_DIRECTORY}" -type f -name "${DUMP_DATABASE}.${TAG}.*.sql.gz" | sort | head -n -${KEEP_DUMPS} | xargs --no-run-if-empty rm | |
| # How to restore a dump: zcat /data/mariadb_backup/db_test.hourly.2024-03-28_15-13.sql.gz | mysql -u 'root' -p db_test |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment