Skip to content

Instantly share code, notes, and snippets.

@vdakalov
Created September 2, 2016 15:20
Show Gist options
  • Select an option

  • Save vdakalov/4d43d992159f0f675f68c7b6982213e1 to your computer and use it in GitHub Desktop.

Select an option

Save vdakalov/4d43d992159f0f675f68c7b6982213e1 to your computer and use it in GitHub Desktop.
mysql dumper
#!/bin/bash
DB_HOST=$1
DB_PORT=$2
DB_USER=$3
DB_PASS=$4
DB_NAME=$5
DUMP_DIR=$6
DUMP_TRAIN=$7
DUMP_PREFIX=$8
DUMP_STAMP=$(date +%d.%m.%Y_%H.%M.%S)
function usage {
echo 'Usage dumper.sh DB_HOST DB_PORT DB_USER DB_PASS DB_NAME DUMP_DIRECTORY [DUMP_TRAIN, DUMP_PREFIX]'
echo 'Where optional'
echo ' DUMP_TRAIN - number of stored files, should >0 (rest will be deleted)'
echo ' DUMP_PREFIX - prefix dump files'
exit 1
}
([[ -z "${DB_HOST}" ]] || [[ -z "${DB_PORT}" ]] || [[ -z "${DB_USER}" ]] || [[ -z "${DB_PASS}" ]] || [[ -z "${DB_NAME}" ]] || [[ -z "${DUMP_DIR}" ]]) && usage
[[ -d ${DUMP_DIR} ]] || mkdir -p ${DUMP_DIR} || exit 2
DUMP_DIR=${DUMP_DIR%/}
DUMP_FILE=${DUMP_DIR}/${DUMP_PREFIX}${DUMP_STAMP}-${DB_NAME}.sql
mysqldump\
--host=${DB_HOST}\
--port=${DB_PORT}\
--user=${DB_USER}\
--password=${DB_PASS}\
${DB_NAME} > ${DUMP_FILE}
if ! [ -z "${DUMP_TRAIN}" ] && [ ${DUMP_TRAIN} -gt 0 ]; then
DUMP_TRAIN=$((${DUMP_TRAIN} + 1));
OLD_DUMPS=$(ls -t ${DUMP_DIR} | grep -E "${DUMP_PREFIX}.*${DB_NAME}.sql" | tail -n +${DUMP_TRAIN});
for file in ${OLD_DUMPS}; do
rm "${DUMP_DIR}/${file}"
done
fi
c=$(echo "${OLD_DUMPS}" | wc -l)
echo "[$(date +'%d.%m.%Y %H:%M:%S')] dump \"${DB_NAME}\" from [${DB_USER}@${DB_HOST}] to ${DUMP_FILE} and removed ${c} files: "${OLD_DUMPS} >> ~/.dumper.log
@vdakalov
Copy link
Author

vdakalov commented Sep 2, 2016

dumper.sh localhost 3306 root 1 mydb /tmp/dumps 5 db-prefix-

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment