Skip to content

Instantly share code, notes, and snippets.

@lnoering
Last active August 10, 2022 13:17
Show Gist options
  • Save lnoering/7c7bd1a1e9119b2e3cdd8cf357339e76 to your computer and use it in GitHub Desktop.
Save lnoering/7c7bd1a1e9119b2e3cdd8cf357339e76 to your computer and use it in GitHub Desktop.
[Magento 2] - Backup of database or media folder in server
#!/bin/bash
#
# Magento 2 - Backup scripts (database | media)
#
# @author Leonardo <lnoering@gmail.com>
# @version 1.0.0
# UnComment it if bash is lower than 4.x version
shopt -s extglob
################################################################################
# HOW TO INSTALL
################################################################################
## cd /path/to/your/preferred/download/folder
## curl --outpu m2b-script.sh https://gist.githubusercontent.com/lnoering/7c7bd1a1e9119b2e3cdd8cf357339e76/raw/m2b-script.sh
## chmod +x m2b-script.sh
## sudo mv mage2-backup.sh /usr/local/bin/mage2-backup.sh
# check is working
## ./mage2-backup.sh --help
################################################################################
# VARIABLES FOR STRING
################################################################################
_bold=$(tput bold)
_underline=$(tput sgr 0 1)
_reset=$(tput sgr0)
_purple=$(tput setaf 171)
_red=$(tput setaf 1)
_green=$(tput setaf 76)
_tan=$(tput setaf 3)
_blue=$(tput setaf 38)
################################################################################
# SCRIPT DEFAULT FUNCTIONS
################################################################################
# PRINT FUNCTIONS
function _header()
{
printf '\n%s%s========== %s ==========%s\n' "$_bold" "$_purple" "$@" "$_reset"
}
function _arrow()
{
printf '➜ %s\n' "$@"
}
function _success()
{
printf '%s✔ %s%s\n' "$_green" "$@" "$_reset"
}
function _error() {
printf '%s✖ %s%s\n' "$_red" "$@" "$_reset"
}
function _warning()
{
printf '%s➜ %s%s\n' "$_tan" "$@" "$_reset"
}
function _underline()
{
printf '%s%s%s%s\n' "$_underline" "$_bold" "$@" "$_reset"
}
function _bold()
{
printf '%s%s%s\n' "$_bold" "$@" "$_reset"
}
function _note()
{
printf '%s%s%sNote:%s %s%s%s\n' "$_underline" "$_bold" "$_blue" "$_reset" "$_blue" "$@" "$_reset"
}
function _die()
{
_error "$@"
exit 1
}
function _safeExit()
{
exit 0
}
# SHORT FUNCTIONS TO HELP
function _debug()
{
if [[ "$DEBUG" = 1 ]]; then
"$@"
fi
}
function _seekConfirmation()
{
printf '\n%s%s%s' "$_bold" "$@" "$_reset"
read -p " (y/n) " -n 1
printf '\n'
}
function _isConfirmed()
{
if [[ "$REPLY" =~ ^[Yy]$ ]]; then
return 0
fi
return 1
}
function _typeExists()
{
if type "$1" >/dev/null; then
return 0
fi
return 1
}
function _isOs()
{
if [[ "${OSTYPE}" == $1* ]]; then
return 0
fi
return 1
}
function _checkRootUser()
{
if [ "$(whoami)" != 'root' ]; then
echo "You have no permission to run $0 as non-root user. Use sudo"
exit 1;
fi
}
################################################################################
# SCRIPT FUNCTIONS
################################################################################
function _printUsage()
{
echo -n "$(basename "$0") [OPTION]...
Help to Backup Magento 2.
Version $VERSION
Options:
-sd, --src-dir Source directory (from where backup file will be created)
-dd, --dest-dir Destination directory (to where the backup file will be moved)
-bt, --type Backup Type. Default: db
Options:
1. db (for database only)
2. media (for media only)
3. all (for database + media)
-lt, --log-tables Ignore log tables
-h, --help Display this help and exit
-v, --version Output version information and exit
Examples:
$(basename "$0") --src-dir=... --dest-dir=... --type=all --skip-media=1
"
exit 1
}
function processArgs()
{
# Parse Arguments
for arg in "$@"
do
case $arg in
-bt=*|--type=*)
BACKUP_TYPE="${arg#*=}"
;;
-sd=*|--src-dir=*)
SRC_DIR="${arg#*=}"
;;
-dd=*|--dest-dir=*)
DEST_DIR="${arg#*=}"
;;
-bn=*|--backup-name=*)
BACKUP_NAME="${arg#*=}"
;;
-lt=*|--log-tables=*)
DB_IGNORE_LOG_TABLES=1
;;
--debug)
DEBUG=1
;;
-h|--help)
_printUsage
;;
*)
_printUsage
;;
esac
done
validateArgs
sanitizeArgs
}
function validateArgs()
{
ERROR_COUNT=0
if [[ -z "$BACKUP_TYPE" ]]; then
_error "Backup type parameter missing."
ERROR_COUNT=$((ERROR_COUNT + 1))
fi
if [[ ! -z "$BACKUP_TYPE" && "$BACKUP_TYPE" != @(db|media|all) ]]; then
_error "Backup type must be one of db|media|all."
ERROR_COUNT=$((ERROR_COUNT + 1))
fi
if [[ -z "$SRC_DIR" ]]; then
_error "Source directory parameter missing."
ERROR_COUNT=$((ERROR_COUNT + 1))
fi
if [[ ! -z "$SRC_DIR" && ! -f "$SRC_DIR/app/etc/env.php" ]]; then
_error "Source directory must be Magento 2 root folder."
ERROR_COUNT=$((ERROR_COUNT + 1))
fi
if [[ -z "$DEST_DIR" ]]; then
_error "Destination directory parameter missing."
ERROR_COUNT=$((ERROR_COUNT + 1))
fi
if [[ ! -z "$DEST_DIR" ]] && ! mkdir -p "$DEST_DIR"; then
_error "Unable to create destination directory."
ERROR_COUNT=$((ERROR_COUNT + 1))
fi
[[ "$ERROR_COUNT" -gt 0 ]] && exit 1
}
function sanitizeArgs()
{
# remove trailing /
if [[ ! -z "$SRC_DIR" ]]; then
SRC_DIR="${SRC_DIR%/}"
fi
if [[ ! -z "$DEST_DIR" ]]; then
DEST_DIR="${DEST_DIR%/}"
fi
}
function prepareBackupName()
{
if [[ -z "$BACKUP_NAME" ]]; then
DATETIME=$(date +"%Y-%m-%d-%H-%M-%S")
BACKUP_NAME=$DATETIME
fi
}
function prepareMediaFilename()
{
MEDIA_BACKUP_FILE="${DEST_DIR}/m2b-backup-media.${BACKUP_NAME}.tar.gz"
}
function prepareDatabaseFilename()
{
DB_BACKUP_FILE="${DEST_DIR}/m2b-backup-database.${BACKUP_NAME}.sql.bz2"
}
function createDbBackup()
{
_success "Dumping MySQL..."
local host username password dbName
# host=$(grep host "${SRC_DIR}/app/etc/env.php" | cut -d "'" -f 4)
DB_DATA=$(grep -E "db..=>" "${SRC_DIR}/app/etc/env.php" -A 15)
# host=$(grep "host" | echo $DB_DATA | cut -d "'" -f 4)
host=$(grep host <<< "$DB_DATA" | cut -d "'" -f 4)
username=$(grep username <<< "$DB_DATA" | cut -d "'" -f 4)
password=$(grep password <<< "$DB_DATA" | cut -d "'" -f 4)
dbName=$(grep dbname <<< "$DB_DATA" | cut -d "'" -f 4)
IGNORED_TABLES_STRING=''
if [[ "$DB_IGNORE_LOG_TABLES" = 1 ]]; then
ignoreDatabaseTables $dbName
fi
{
mysqldump \
-h "$host" \
-u "$username" \
-p"$password" \
"$dbName" \
--single-transaction \
--no-data \
--no-tablespaces \
| bzip2 -c9 > "$DB_BACKUP_FILE" \
&& \
mysqldump \
-h "$host" \
-u "$username" \
-p"$password" \
"$dbName" \
--no-tablespaces \
$IGNORED_TABLES_STRING
} \
| bzip2 -c9 > "$DB_BACKUP_FILE"
_success "Done!"
}
function ignoreDatabaseTables()
{
EXCLUDED_TABLES=(
log_customer
log_visitor
log_visitor_info
log_url
log_url_info
log_quote
report_viewed_product_index
report_compared_product_index
report_event
catalog_compare_item
dataflow_batch_export
dataflow_batch_import
log_quote
log_summary
log_summary_type
log_visitor_online
)
for TABLE in "${EXCLUDED_TABLES[@]}"
do :
IGNORED_TABLES_STRING+=" --ignore-table=$@.${TABLE}"
done
}
function createMediaBackup()
{
_success "Archiving Media..."
tar -zcf $MEDIA_BACKUP_FILE -C ${SRC_DIR} pub/media
_success "Done!"
}
function printSuccessMessage()
{
_success "Magento2 Backup Completed!"
echo "################################################################"
echo ""
echo " >> Backup Type : ${BACKUP_TYPE}"
echo " >> Backup Source : ${SRC_DIR}"
if [[ $BACKUP_TYPE = @(db|database|all) ]]; then
echo " >> Database Dump File : ${DB_BACKUP_FILE}"
fi
if [[ $BACKUP_TYPE = @(media|all) ]]; then
echo " >> Media Archive File : ${MEDIA_BACKUP_FILE}"
fi
echo ""
echo "################################################################"
}
################################################################################
# Main
################################################################################
export LC_CTYPE=C
export LANG=C
DEBUG=0
_debug set -x
VERSION="1.0.0"
SRC_DIR=
DEST_DIR=
BACKUP_TYPE=db
BACKUP_NAME=
DB_BACKUP_FILE=
DB_IGNORE_LOG_TABLES=0
MEDIA_BACKUP_FILE=
function main()
{
[[ $# -lt 1 ]] && _printUsage
processArgs "$@"
prepareBackupName
if [[ "$BACKUP_TYPE" = @(database|db|all) ]]; then
prepareDatabaseFilename
createDbBackup
fi
if [[ "$BACKUP_TYPE" = @(media|all) ]]; then
prepareMediaFilename
createMediaBackup
fi
printSuccessMessage
exit 0
}
main "$@"
_debug set +x
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment