Last active
December 28, 2021 01:01
-
-
Save antoniosmgatto/724f0c7061f2323553d2f6a36a733537 to your computer and use it in GitHub Desktop.
Mysql backup script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# errexit -> exit when any command fails | |
set -o errexit | |
# will fails exit if an pipe command fails | |
set -o pipefail | |
# nounset -> exit when an unsed variable is used | |
set -o nounset | |
db_host="127.0.0.1" | |
while getopts ":u:p:d:h:" o; do | |
case "${o}" in | |
u) db_username=${OPTARG};; | |
p) db_password=${OPTARG};; | |
d) db_database=${OPTARG};; | |
h) db_host=${OPTARG};; | |
*) echo "Usage: $0 -u username -p password -d database_name [-h db.example.com]" 1>&2; exit 1;; | |
esac | |
done | |
readonly timestamp=$(date +%F_%H-%M) | |
readonly storage_path="/var/app/backup" | |
readonly dumpfile_path="$storage_path/${db_database}_${timestamp}.sql" | |
readonly compressed_dump_path="${dumpfile_path}.gz" | |
if [ -d != $storage_path ]; then | |
mkdir -p $storage_path; | |
fi | |
# dump database | |
mysqldump -h $db_host -u $db_username -p$db_password $db_database > $dumpfile_path | |
# compress file | |
gzip -9 $dumpfile_path | |
echo "Backup file created: $compressed_dump_path !!!" | |
# cleaning up old backups | |
find $storage_path -iname "${db_database}*.sql.gz" -mtime +3 -exec rm {} \; | |
exit 0; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment