#!/bin/sh # Configuration # Files will be named BASE_DIR/PREFIXEbasenameSUFFIXE BASE_DIR="/var/backups/bdd" MYSQL_EXTRA_ARGS="" # Pas d'option --skip-definer ? # - sed 's/^CREATE DEFINER=`[^ ]\+` /CREATE /' # ne marche que pour CREATE FUNCTION et similaire # - sed 's/ DEFINER=`[^ ]\+` / DEFINER=CURRENT_USER /' # marche aussi pour les commentaires. MYSQLDUMP_EXTRA_ARGS="--add-drop-table --routines --events --triggers --single-transaction" PREFIXE="sauv_mysql_" SUFFIXE=_$( date +%Y%m%d-%H%M%S ).sql.gz NB_DAYS_BEFORE_DELETION="30" BASES_EXCLUDED="information_schema performance_schema" # Small note for a backup of a random directory in crontab # test -d /var/backups/www && cd /var/www && tar -czf /var/backups/www/www_$( date +\%Y\%m\%d-\%H\%M\%S ).tar.gz ./ && find /var/backups/www -maxdepth 1 -name 'www_*' -mtime +10 -delete # Stop at first non-catched error set -e # # Help function # usage() { TMP_BASES_EXCLUDED="$( echo "$BASES_EXCLUDED" | tr '\n' " " )" cat </dev/null 2>&1 # # Parameters management # while getopts hd:B:p:ze:x:X: f; do case "$f" in 'h') usage exit ;; 'd') NB_DAYS_BEFORE_DELETION="$OPTARG" ;; 'B') BASE_DIR="$OPTARG" ;; 'p') PREFIXE="$OPTARG" ;; 'z') BASES_EXCLUDED="" ;; 'e') if [ -z "$BASES_EXCLUDED" ]; then BASES_EXCLUDED="$OPTARG" else BASES_EXCLUDED="$( printf "%s\n%s" "$BASES_EXCLUDED" "$OPTARG" )" fi ;; 'x') MYSQL_EXTRA_ARGS="$OPTARG" ;; 'X') MYSQLDUMP_EXTRA_ARGS="$OPTARG" ;; \?) usage exit 1 ;; esac done shift $( expr $OPTIND - 1 ) # Initial checks if [ ! -d "$BASE_DIR" ]; then echo "ERREUR : répertoire de sauvegarde inexistant : $BASE_DIR ." >&2 exit 1 fi if [ -z "$@" ]; then # Listing des bases à sauvegarder BASES="$( mysql $MYSQL_EXTRA_ARGS -Bse "SHOW DATABASES;" )" else BASES="$@" fi # Loop on bases' names # We try to have a little fun here : MySQL can be quite laxist # on base names, so we use as a separator. Quite a gymnastic # ensue :) printf "%s\n" "$BASES" | while read BASENAME; do IFS=" " for EXCLUDED_NAME in $BASES_EXCLUDED; do if [ "$BASENAME" = "$EXCLUDED_NAME" ]; then unset IFS continue 2 fi done unset IFS mysqldump $MYSQLDUMP_EXTRA_ARGS "$BASENAME" | gzip -c > "$BASE_DIR/$PREFIXE$BASENAME$SUFFIXE" done # Deletion of old backups if [ "$NB_DAYS_BEFORE_DELETION" -gt "0" ]; then find $BASE_DIR -maxdepth 1 -name "$PREFIXE*" -mtime +$NB_DAYS_BEFORE_DELETION -delete fi