docker-mysql-cron-backup/backup.sh

58 lines
2.4 KiB
Bash
Raw Normal View History

#!/bin/bash
# Get hostname: try read from file, else get from env
2022-10-16 21:46:12 +02:00
[ -z "${MYSQL_HOST_FILE}" ] || { MYSQL_HOST=$(head -1 "${MYSQL_HOST_FILE}"); }
[ -z "${MYSQL_HOST}" ] && { echo "=> MYSQL_HOST cannot be empty" && exit 1; }
# Get username: try read from file, else get from env
[ -z "${MYSQL_USER_FILE}" ] || { MYSQL_USER=$(head -1 "${MYSQL_USER_FILE}"); }
[ -z "${MYSQL_USER}" ] && { echo "=> MYSQL_USER cannot be empty" && exit 1; }
# Get password: try read from file, else get from env, else get from MYSQL_PASSWORD env
[ -z "${MYSQL_PASS_FILE}" ] || { MYSQL_PASS=$(head -1 "${MYSQL_PASS_FILE}"); }
[ -z "${MYSQL_PASS:=$MYSQL_PASSWORD}" ] && { echo "=> MYSQL_PASS cannot be empty" && exit 1; }
# Get database name(s): try read from file, else get from env
# Note: when from file, there can be one database name per line in that file
[ -z "${MYSQL_DATABASE_FILE}" ] || { MYSQL_DATABASE=$(cat "${MYSQL_DATABASE_FILE}"); }
# Get level from env, else use 6
[ -z "${GZIP_LEVEL}" ] && { GZIP_LEVEL=6; }
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")"
2022-06-14 17:18:01 +02:00
DATABASES=${MYSQL_DATABASE:-${MYSQL_DB:-$(mysql -h "$MYSQL_HOST" -P "$MYSQL_PORT" -u "$MYSQL_USER" -p"$MYSQL_PASS" $MYSQL_SSL_OPTS -e "SHOW DATABASES;" | tr -d "| " | grep -v Database)}}
2019-07-28 15:58:55 +02:00
for db in ${DATABASES}
2017-04-16 11:29:31 +02:00
do
2021-12-30 18:38:06 +01:00
if [[ "$db" != "information_schema" ]] \
&& [[ "$db" != "performance_schema" ]] \
&& [[ "$db" != "mysql" ]] \
&& [[ "$db" != "sys" ]] \
&& [[ "$db" != _* ]]
then
2018-11-12 21:12:53 +01:00
echo "==> Dumping database: $db"
FILENAME=/backup/$DATE.$db.sql
2022-02-04 20:44:11 +01:00
LATEST=/backup/latest.$db.sql
2022-06-14 17:18:01 +02:00
if mysqldump --single-transaction $MYSQLDUMP_OPTS -h "$MYSQL_HOST" -P "$MYSQL_PORT" -u "$MYSQL_USER" -p"$MYSQL_PASS" $MYSQL_SSL_OPTS "$db" > "$FILENAME"
then
2022-02-04 20:44:11 +01:00
EXT=
if [ -z "${USE_PLAIN_SQL}" ]
then
echo "==> Compressing $db with LEVEL $GZIP_LEVEL"
gzip "-$GZIP_LEVEL" -f "$FILENAME"
EXT=.gz
FILENAME=$FILENAME$EXT
LATEST=$LATEST$EXT
fi
BASENAME=$(basename "$FILENAME")
echo "==> Creating symlink to latest backup: $BASENAME"
2018-11-08 14:34:29 +01:00
rm "$LATEST" 2> /dev/null
2022-02-04 20:44:11 +01:00
cd /backup || exit && ln -s "$BASENAME" "$(basename "$LATEST")"
if [ -n "$MAX_BACKUPS" ]
then
# Execute the delete script, delete older backup or other custom delete script
/delete.sh $db $EXT
fi
else
rm -rf "$FILENAME"
fi
fi
done
2019-07-28 15:58:55 +02:00
echo "=> Backup process finished at $(date "+%Y-%m-%d %H:%M:%S")"