#!/bin/bash
  ##autor by huwj 20161019
  MysqlDump='/usr/bin/mysqldump'
  hostPort='localhost'
  database='dbName'
  dbPath='/data/mysqlBak/dbName'
  uName='dbName'
  uPass='dbPasswd'
  Date=`date '+%Y%m%d%H%M'`
  backPath='/data/mysqlBak/mysqlBack'
  runLog="$backPath/log/run.log"
  RM='/bin/rm'
  MV='/bin/mv'
  MKDIR='/bin/mkdir'
  Find='/bin/find'
  Tar='/bin/tar'
  echo 'date=='$Date
  #删除15天之前的备份文件 此方法根据文件生成时间来删除,若中间存在备份失败,容易误删除,风险较高,慎用!
  delBackFile(){
  cd $backPath
  $Find  -mtime +15 |xargs rm -rf
  }
  #delBackFile
  #开始执行备份操作
  # the directory for story the newest backupss
  test ! -d "$backPath/backup.0/" && $MKDIR -p "$backPath/backup.0/"
  backUpMongo(){
  if [ ! -d "$dbPath/$database" ]; then
  echo "$Date starting to backup ..." >> $runLog
  $MysqlDump -h $hostPort -u $uName -p$uPass $database  > $dbPath/$database.sql
  cd $dbPath
  echo "$Date starting to tar backfile..." >> $runLog
  $Tar -zcvf  $backPath/backup.0/$database.$Date.tar.gz $database.sql
  if [ -f "$backPath/backup.0/$database.$Date.tar.gz" ];then
  $RM -rf $dbPath/$database.sql
  echo "$Date backSuccess ,starting to mv backfile..." >> $runLog
  # delete the oldest backup
  test -d "$backPath/backup.15/" && $RM -rf "$backPath/backup.15"
  # rotate backup directory
  echo "$Date mv success ,starting to mv oldFile ....." >> $runLog
  for int in  15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
  do
  if ( test -d "$backPath"/backup."$int" )
  then
  next_int=`expr $int + 1`
  $MV "$backPath"/backup."$int" "$backPath"/backup."$next_int"
  fi
  done
  fi
  else
  echo "$Date rm backfile ...." >> $runLog
  $RM -rf $dbPath/$database.sql
  fi
  }
  backUpMongo