Analysis of a Linux Periodic Auto-Backup Script

     In our network maintenance work, we often need to back up data. While the task is not complicated, it is quite time-consuming. Here I share a Linux backup script that easily achieves automatic backups and can retain backup archives for N days. This script consists of two files: an executable file backup.sh and a backup project file project.lst.

  #backup.sh

  – Important Variable Names and Their Roles

  LogFile Log file

  SourceDir Directory to be backed up

  BakDir Destination directory for backups

  RetainDay Number of days to retain backup archive files

  ProjectLst Configuration file for the backup project

  Code:

  #!/bin/bash

  #author: InBi

  #date: 2011-07-28

  #role: backup files periodically.

  ##################################################

  LogFile=/backup/log/`date +"%Y-%m"`.log

  DATE=`date +"%Y-%m-%d"`

  SourceDir=/var/RDfile

  BakDir=/backup

  RetainDay=20

  ProjectLst=/backup/project.lst

  ##################################################

  echo "backup start at $(date +"%Y-%m-%d %H:%M:%S")" > $LogFile

  echo "————————————————–" >> $LogFile

  cd $BakDir

  PROJECTLIST=`cat $ProjectLst`

  for Project in $PROJECTLIST

  do

  ProjectData=$SourceDir/$Project

  DestDir=$BakDir/$Project

  PackFile=$DATE.$Project.tgz

  if [ -f $BakDir/$PackFile ]

  then

  echo "backup file have exist !" >>$LogFile

  else

  cp -RHpf $ProjectData $DestDir > /dev/null

  tar -zcvf $PackFile $Project > /dev/null

  echo "backup $Project done into $PackFile ">>$LogFile

  rm -rf $Project

  fi

  OldFile="$BakDir/"$(date –date="$RetainDay days ago" +"%Y-%m-%d").$Project.tgz

  if [ -f $OldFile ]

  then

  rm -f $OldFile > /dev/null

  echo "[$OldFile],Delete Old File Success!" >> $LogFile

  fi

  echo " " >> $LogFile

  done

  echo "————————————————–" >> $LogFile

  echo "backup end at $(date +"%Y-%m-%d %H:%M:%S")" >> $LogFile

  echo " " >> $LogFile

  exit 0

  # project.lst : This file is easy to understand — it is simply a text file where each line represents a project, i.e., the file or directory under the directory you want to back up.

  onu_arm

  onu_voip

  onu_wifi

  5xxx

  7xxx

  8xxx

  nms

Leave a Comment

Your email address will not be published.