Skip to content

Instantly share code, notes, and snippets.

@ahmu83
Created May 20, 2024 14:04
Show Gist options
  • Save ahmu83/39f0d645e63550d66fd020dd170c2f52 to your computer and use it in GitHub Desktop.
Save ahmu83/39f0d645e63550d66fd020dd170c2f52 to your computer and use it in GitHub Desktop.
This is a Bash script designed to export MySQL databases into various formats including plain SQL, compressed ZIP, and GZIP files.
#!/bin/bash
# USAGE:
#
# sh export-mysql-db.sh
# bash export-mysql-db.sh
#
# OR
#
# chmod +x export-mysql-db.sh
# ./export-mysql-db.sh
# Set database parameters
DB_USER="your_username"
DB_PASS="your_password" # Be cautious with storing passwords in scripts
DB_HOST="localhost" # Default to localhost, change as needed
DB_NAME="your_database_name" # Database name
EXPORT_FORMAT="sql" # Options: sql, zip, gz
# Set the filename based on chosen format
FILENAME="$DB_NAME-$(date +%Y%m%d_%H%M%S)"
case $EXPORT_FORMAT in
"sql")
FILENAME="$FILENAME.sql"
;;
"zip")
FILENAME="$FILENAME.sql.zip"
;;
"gz")
FILENAME="$FILENAME.sql.gz"
;;
esac
# Export the database
echo "Exporting database '$DB_NAME' to $FILENAME..."
if [[ "$EXPORT_FORMAT" == "sql" ]]; then
mysqldump -u "$DB_USER" -p"$DB_PASS" -h "$DB_HOST" "$DB_NAME" > "$FILENAME"
elif [[ "$EXPORT_FORMAT" == "zip" ]]; then
mysqldump -u "$DB_USER" -p"$DB_PASS" -h "$DB_HOST" "$DB_NAME" | zip -9 - "$FILENAME" -
elif [[ "$EXPORT_FORMAT" == "gz" ]]; then
mysqldump -u "$DB_USER" -p"$DB_PASS" -h "$DB_HOST" "$DB_NAME" | gzip > "$FILENAME"
fi
if [ $? -eq 0 ]; then
echo "Database export successful."
else
echo "Database export failed."
fi
@ahmu83
Copy link
Author

ahmu83 commented May 20, 2024

This is a Bash script designed to export MySQL databases into various formats including plain SQL, compressed ZIP, and GZIP files.

It dynamically generates filenames based on the database name and the date and time of the export to avoid overwriting previous backups.

Ideal for developers and database administrators who require reliable tools for regular backups or migrating database contents between environments.

Usage Instructions

sh export-mysql-db.sh

OR

chmod +x export-mysql-db.sh ./export-mysql-db.sh

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