docker-mysql-cron-backup/backup.sh

39 lines
1.5 KiB
Bash
Raw Normal View History

#!/bin/bash
[ -z "${MYSQL_USER}" ] && { echo "=> MYSQL_USER cannot be empty" && exit 1; }
[ -z "${MYSQL_PASS:=$MYSQL_PASSWORD}" ] && { echo "=> MYSQL_PASS cannot be empty" && exit 1; }
DATE=$(date +%Y%m%d%H%M)
2018-11-12 21:12:53 +01:00
echo "=> Backup started at $(date "+%Y-%m-%d %H:%M:%S")"
databases=${MYSQL_DATABASE:-${MYSQL_DB:-$(mysql -h "$MYSQL_HOST" -P "$MYSQL_PORT" -u "$MYSQL_USER" -p"$MYSQL_PASS" -e "SHOW DATABASES;" | tr -d "| " | grep -v Database)}}
2017-04-16 11:29:31 +02:00
for db in $databases
do
if [[ "$db" != "information_schema" ]] && [[ "$db" != "performance_schema" ]] && [[ "$db" != "mysql" ]] && [[ "$db" != _* ]]
then
2018-11-12 21:12:53 +01:00
echo "==> Dumping database: $db"
FILENAME=/backup/$DATE.$db.sql
LATEST=/backup/latest.$db.sql.gz
2018-11-12 21:12:53 +01:00
if mysqldump -h "$MYSQL_HOST" -P "$MYSQL_PORT" -u "$MYSQL_USER" -p"$MYSQL_PASS" --databases "$db" $MYSQLDUMP_OPTS > "$FILENAME"
then
gzip -f "$FILENAME"
2018-11-12 21:12:53 +01:00
echo "==> Creating symlink to latest backup: $(basename "$FILENAME".gz)"
2018-11-08 14:34:29 +01:00
rm "$LATEST" 2> /dev/null
2018-11-12 21:12:12 +01:00
cd backup && ln -s $(basename "$FILENAME".gz) $(basename "$LATEST") && cd ..
else
rm -rf "$FILENAME"
fi
fi
done
if [ -n "$MAX_BACKUPS" ]
then
2018-11-12 21:12:53 +01:00
echo "=> Max number of backups ("$MAX_BACKUPS") reached. Deleting oldest backups"
while [ "$(find /backup -maxdepth 1 -name "*.sql.gz" -type f | wc -l)" -gt "$MAX_BACKUPS" ]
do
TARGET=$(find /backup -maxdepth 1 -name "*.sql.gz" -type f | sort | head -n 1)
rm -rf "$TARGET"
2018-11-12 21:12:53 +01:00
echo "==> Backup $TARGET has been deleted"
done
fi
2018-11-12 21:12:53 +01:00
echo "=> Backup process finished at echo $(date "+%Y-%m-%d %H:%M:%S")"