Skip to content

Instantly share code, notes, and snippets.

@raflymln
Last active September 22, 2022 10:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raflymln/263fe23f6b68b16a561f73bb71796a04 to your computer and use it in GitHub Desktop.
Save raflymln/263fe23f6b68b16a561f73bb71796a04 to your computer and use it in GitHub Desktop.
MySQL Backup Script
#!/bin/bash
# Usage: ./script.sh <username> <password> <host> <port> <target-folder (optional)>
# Example: ./script.sh admin admin 127.0.0.1 3306 /var/backups/mysql
# Default dump folder is /var/backups/mysql
if [ -z "$1" ]; then
echo "The usage is: <username> <password> <host> <port> <target-folder (optional)>";
exit;
elif [ -z "$2" ]; then
echo "[ERROR] MySQL connection 'password' is not provided";
exit;
elif [ -z "$3" ]; then
echo "[ERROR] MySQL connection 'host' is not provided";
exit;
elif [ -z "$4" ]; then
echo "[ERROR] MySQL connection 'port' is not provided";
exit;
fi;
CLI_LIST="mysql mysqldump";
for CLI in $CLI_LIST; do
if ! command -v $CLI >/dev/null 2>&1; then
echo "'$CLI' is not found";
exit;
fi;
done
DESIRED_TARGET_FOLDER="$5";
if [ -z "$DESIRED_TARGET_FOLDER" ]; then
DESIRED_TARGET_FOLDER="/var/backups/mysql";
elif [[ "$DESIRED_TARGET_FOLDER" == */ ]]; then
echo "[ERROR] The desired target folder should not end with /";
exit;
fi;
CURRENT_DATE="$(date +"%H").$(date +"%M").$(date +"%S")-$(date +%F)"
TARGET_FOLDER="$DESIRED_TARGET_FOLDER/$CURRENT_DATE"
mkdir -p $TARGET_FOLDER;
echo "[DEBUG] Creating MySQL dump folder on $TARGET_FOLDER";
echo "[DEBUG] Running MySQL backup for Host '$3' on Port '$4' using Username '$1'";
MYSQL_CONNECTION_CONFIG="-u '$1' -p$2 -h $3 -P $4";
DATABASES=`mysql $MYSQL_CONNECTION_CONFIG -e "show databases" | sed -n '2,$ p'`;
for DATABASE in $DATABASES; do
{ #try
echo "[DEBUG] Creating SQL file from database '$DATABASE' on $TARGET_FOLDER/$DATABASE.sql";
mysqldump $MYSQL_CONNECTION_CONFIG $DATABASE > $TARGET_FOLDER/$DATABASE.sql;
} || { #catch
echo "[ERROR] Failed to create SQL file from database '$DATABASE'"
}
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment