Skip to content

Instantly share code, notes, and snippets.

@efann
Last active November 7, 2022 20:58
Show Gist options
  • Select an option

  • Save efann/1d61307906b41a13f972 to your computer and use it in GitHub Desktop.

Select an option

Save efann/1d61307906b41a13f972 to your computer and use it in GitHub Desktop.
#!/bin/bash
# License: Eclipse Public License - v 2.0 (https://www.eclipse.org/org/documents/epl-2.0/EPL-2.0.html)
# Updated on November 7, 2022
# Designed to backup websites that are in /var/www and use MySQL.
# Recommend the root user.
# In order to get rid of the following message
# Warning: Using a password on the command line interface can be insecure.
# I ran the following command
# mysql_config_editor set --login-path=<alias> --user=<user> -p
# Example of use
# mysql --login-path=<alias>
LOGIN_PATH="<alias>"
MYSQL_HOST="localhost"
MYSQL="$(which mysql)"
MYSQLDUMP="$(which mysqldump)"
BACKUP_ROOT="/backup"
BACKUP_FOLDER="$BACKUP_ROOT/current"
# By the way, the days will be 08, 09, 10, 11, etc.
ARCHIVE_FOLDER="$BACKUP_ROOT/day_$(date +%d)"
GZIP="$(which gzip)"
GUNZIP="$(which gunzip)"
TAR="$(which tar)"
### See comments below ###
if [ ! -d "$BACKUP_FOLDER" ]
then
mkdir -p "$BACKUP_FOLDER"
fi
if [ ! -d "$ARCHIVE_FOLDER" ]
then
mkdir -p "$ARCHIVE_FOLDER"
fi
echo -e "====================================="
# Batch, silent, execute and exit.
laDatabases="$($MYSQL --login-path=$LOGIN_PATH -h $MYSQL_HOST -Bse 'show databases')"
# Do not put quotes around $laDatabases: otherwise it will be treated
# as one variable and will not be split between new lines
for lcDatabase in $laDatabases;
do
if [[ "$lcDatabase" != "performance_schema" ]] && [[ "$lcDatabase" != "information_schema" ]]
then
lcFile="$BACKUP_FOLDER/sql.mysql.$lcDatabase.gz"
echo -e "$lcDatabase dump to $lcFile"
$MYSQLDUMP --login-path=$LOGIN_PATH -h $MYSQL_HOST --events "$lcDatabase" | $GZIP > "$lcFile"
fi
done
laFolders="$(find /var/www/ -type d -path */public_html)"
# DO NOT USE the 7-zip format for backup purpose on Linux/Unix because :
# - 7-zip does not store the owner/group of the file.
for lcFolder in $laFolders;
do
echo -e "$lcFolder"
lcDirName="$(dirname $lcFolder)"
lcFile="$BACKUP_FOLDER/code.$(basename $lcDirName).tar.gz"
rm -fv "$lcFile"
$TAR -zcf "$lcFile" "$lcFolder"
$GUNZIP -tv "$lcFile"
done
echo -e "====================================="
echo -e "Testing backup file in the archive folder, $BACKUP_FOLDER. . . ."
for lcFile in "$BACKUP_FOLDER"/*.gz;
do
$GUNZIP -tv "$lcFile"
done
echo -e "====================================="
echo -e "Copying backup files to the archive folder, $ARCHIVE_FOLDER. . . ."
pushd "$BACKUP_FOLDER"
cp -rv * "$ARCHIVE_FOLDER"
popd
echo -e "====================================="
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment