Skip to content

Instantly share code, notes, and snippets.

@cnicodeme
Last active December 19, 2015 05:59
Show Gist options
  • Save cnicodeme/5907921 to your computer and use it in GitHub Desktop.
Save cnicodeme/5907921 to your computer and use it in GitHub Desktop.
Saves database listed in each databases.bk files located in all the folders starting from a base path.
#!/bin/bash
#
# --------------------------------------------------------------------
# This is a free shell script under GNU GPL version 3.0 or above
# Copyright (C) 2005 ReFlectiv project.
# Feedback/comment/suggestions : http://www.reflectiv.net/
# -------------------------------------------------------------------------
#
# This script automatically backups the database based on each folder
# on the given path and the directive for which db to save
#
###################################
# Please provides these variables #
###################################
BASE_PATH="/srv/www/";
DATABASE_FILENAME="databases.bk";
BACKUP_FOLDER="backups/databases/";
FILE_OWNER="backup";
FILE_GROUP="www-data";
DB_USER="root";
DB_PASS="";
###################################
for folder in $(find $BASE_PATH -mindepth 1 -maxdepth 1 -type d); do
cd $folder
if [[ -f "$folder/$DATABASE_FILENAME" ]]; then
if [ ! -d $BACKUP_FOLDER ]; then
mkdir -p $BACKUP_FOLDER;
chown -R $FILE_OWNER:$FILE_GROUP $BACKUP_FOLDER;
fi
cd $BACKUP_FOLDER;
for database_name in $(cat $folder/$DATABASE_FILENAME); do
SQL_FILENAME=$(date +"%Y-%m-%d")"-"$database_name".sql";
/usr/bin/mysqldump -u $DB_USER -p$DB_PASS --skip-lock-tables --add-drop-database --add-drop-table --complete-insert --routines --triggers --allow-keywords --max_allowed_packet=50M --force $database_name -R > $SQL_FILENAME;
chown $FILE_OWNER:$FILE_GROUP $SQL_FILENAME;
chmod 740 $SQL_FILENAME;
if [ $(date +%u) != "1" ]; then
rm -f $(date --date '7 days ago' +"%Y-%m-%d")"-"$database_name".sql";
fi
done
# remove all older files than a month
find . -type f -mtime +32 -delete;
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment