mysql-backup/restore-mysql.sh

66 lines
1.5 KiB
Bash
Raw Normal View History

2023-12-26 22:40:54 +02:00
#!/usr/bin/env bash
USER="root"
PASSWORD="secretpass"
OUTPUT_DIR="./output"
HOSTNAME="127.0.0.1"
GZIP_ENABLED="1"
2023-12-26 22:40:54 +02:00
USE_PASSWORD="0"
USE_HOSTNAME="0"
set -a # automatically export all variables
source .env
set +a
if [ "${DEBUG}" -gt "0" ]
then
set -x
fi
2023-12-26 22:40:54 +02:00
PASSWORD_OPTIONS="-p${PASSWORD}"
HOST_OPTIONS="-h ${HOSTNAME}"
if [ "${USE_HOSTNAME}" -eq "0" ]
then
HOST_OPTIONS=""
fi
if [ "${USE_PASSWORD}" -eq "0" ]
then
PASSWORD_OPTIONS=""
fi
databases=$(ls ${OUTPUT_DIR})
for db in ${databases}; do
if [[ "${db}" != "information_schema" ]] && [[ "${db}" != "performance_schema" ]] && [[ "${db}" != "mysql" ]] && [[ "${db}" != _* ]]
then
GZIP="0"
DUMP_DIR="${OUTPUT_DIR}/${db}"
NEWEST_DUMP_FILENAME="$(ls -Art ${OUTPUT_DIR}/${db} | tail -n 1)"
DUMP_FILENAME="${DUMP_DIR}/${NEWEST_DUMP_FILENAME}"
file "${DUMP_FILENAME}" | grep "gzip compressed data" >/dev/null
if [ "$?" -eq "0" ]
then
GZIP_ENABLED="1"
2023-12-26 22:40:54 +02:00
else
GZIP_ENABLED="0"
2023-12-26 22:40:54 +02:00
fi
echo "Restoring database: ${db} from: ${DUMP_FILENAME}"
echo "Trying to create the DB:"
mysql ${HOST_OPTIONS} -u ${USER} ${PASSWORD_OPTIONS} --default-character-set=utf8mb4 -e "CREATE DATABASE ${db} CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
echo "Restoring DB from backup file"
if [ "${GZIP_ENABLED}" -gt "0" ]
2023-12-26 22:40:54 +02:00
then
gunzip "${DUMP_FILENAME}" | mysql ${HOST_OPTIONS} -u ${USER} ${PASSWORD_OPTIONS} --default-character-set=utf8mb4 ${db}
else
cat "${DUMP_FILENAME}" | mysql ${HOST_OPTIONS} -u ${USER} ${PASSWORD_OPTIONS} --default-character-set=utf8mb4 ${db}
fi
fi
done
set +x