IT & + si affinités

Encore un blog de sysadmin … mais pas uniquement ;-)

Script de backup

Voici un petit script qui permet de  « sauvegarder » un répertoire et de gérer la rotation :

#!/bin/bash
# 
# Name : backup_dir.sh
# Author : @Markhor75 
# Last Mod : 2012 10 28
export name=`basename "$0"`

RETENTIONDAYS="7"
MAKEARCHIVE="1"
SOURCE="&&&"
DESTINATION="/var/backups"
DATE="$(date +"%Y%m%d_%H%M")"

if [ $MAKEARCHIVE -eq "1" ]; then
        ARCHIVESTATUS="enabled"
else
        ARCHIVESTATUS="disabled"
fi

usage()
{
   echo "> Make a tar.gz of \"Source dir\" directory in "$DESTINATION" or other specified dir." 
   echo "> Delete archives older than "$RETENTIONDAYS" days."
   echo "> You can change this value with option -r ( 0 won't delete files)."
   echo "> Optionaly make mensual permanent copy, this option is currently "$ARCHIVESTATUS
   echo ">"
   echo "> Usage:"
   echo ">    $name -h                      Show this help."
   echo ">    $name -s Source dir [-d Destination dir] [-r 7]"
   echo "> Default Destination dir is "$DESTINATION
}

if [ "$1" != "-s" ]; then
   usage
   exit
fi
while getopts s:d:hr: opt
do
   case "$opt" in
      s) SOURCE=$OPTARG;;
      d) DESTINATION=$OPTARG;;
      r) ((RETENTIONDAYS=OPTARG+0));;
      h)
        usage
        exit
        ;;
      \?)
        usage
        exit
         ;;
   esac
done

if [ ! -d $SOURCE ]; then
        usage
        exit
fi

# Creating destination dir if needed
if [ ! -d $DESTINATION ]; then
        mkdir $DESTINATION
fi

CURRENT_DIR=`pwd`
cd $SOURCE
ARCHIVENAME=${PWD##*/}"_"$DATE".tar.gz"

tar -cvzf $DESTINATION"/"$ARCHIVENAME $SOURCE 2>&1 1>/dev/null

if [ "$MAKEARCHIVE" == "1" ]; then
        ARCHIVEMENSUEL=$DESTINATION"/mensuel"
        if [ ! -d $ARCHIVEMENSUEL ]; then
                mkdir $ARCHIVEMENSUEL
        fi
fi

# If RETENTIONDAYS value is greater than 1, we delete older files
if [ "$RETENTIONDAYS" -gt "1" ] ; then
        find $DESTINATION -maxdepth 1 -ctime +$RETENTIONDAYS -type f -exec rm {} \;
fi

cd $CURRENT_DIR
exit 0;