日期:2014-05-16  浏览次数:20814 次

mysql自动备份与恢复shell脚本(2)
backup_mysql.sh

#!/bin/sh

# set -x

## this script is for auto mysql backup
## log file: /opt/alu/logs/3rd_party/mysql/backup.log

declare db_names
LOG_FILE=/opt/alu/logs/3rd_party/mysql/backup.log
TIME=`date +"%Y%m%d%H%M%S"`
DUMP_FILE=".sql"
TGZ_FILE=".tgz"
SHELL_DIR=/opt/alu/shell/sysmgt

log_success_msg(){
  echo " SUCCESS! $@"
}

log_failure_msg(){
  echo " ERROR! $@"
}


p_echo(){
  echo >> ${LOG_FILE}
  echo "-------------Backup-------------" >> ${LOG_FILE}
  echo `date +"%Y-%m-%d %H:%M:%S"` >> ${LOG_FILE}
  echo "-------------Backup-------------" >> ${LOG_FILE}
  echo >> ${LOG_FILE}
}

## check mysql pid, and kill it
checkProcess(){
  PIDS=`ps -ef|grep mysqld|grep -v grep|grep 3306|awk '{print $2}'`
  if [ -n ${PIDS} ]; then
    for pid in ${PIDS}
    do
      kill -9 ${pid}
    done
  fi   
}

## check mysql service, make sure it's alive
checkStatus(){
  `mysqladmin ping > /dev/null 2>&1`
  if [[ $? != 0 ]]; then
    checkProcess
    echo "mysql is not alive,will be start now!" >> ${LOG_FILE}
    ${SHELL_DIR}/mysql_supervise.sh start >> ${LOG_FILE} 2>&1
  fi
  `mysqladmin ping > /dev/null 2>&1`
  if [[ $? != 0 ]];then
    echo "Mysql server error"
    exit 1
  fi
}

## find all database name
find_db_names(){
  DB_NAMES_ALL=$(mysql -e "show databases;")
  index=0
  for DB in ${DB_NAMES_ALL}
  do
    if [[ "$DB" != "Database" && "$DB" != "information_schema" && "$DB" != "performance_schema" ]];then
      db_names[$index]=$DB
      let index++
    fi
  done
}
 
## tgz file today exists,delete it
delete_old_file(){
  if [ -f $1 ]; then
    echo "[$1] Backup file is exists,will be delete" >> ${LOG_FILE}
    rm -f $1 > /dev/null 2>&1
  fi
}

## mysqldump function
func_mysqldump(){
  db_dump_file=$1$DUMP_FILE
  db_tgz_file=$1$TGZ_FILE

  mysqldump -q --add-drop-table --single-transaction --lock-tables=false $1 > $db_dump_file
  tar -czvf $db_tgz_file $db_dump_file > /dev/null
  echo "[$1] Backup success!"
  echo "[${db_tgz_file}] Backup success!" >> ${LOG_FILE}   
  rm -rf $db_dump_file > /dev/null 2>&1 
}


## backup all db
backup_all(){
  # find all db name
  find_db_names
  echo
  echo -e "Please enter the directory for save the backup file:"  
  read dir
  if [[ ! -d $dir ]];then
    log_failure_msg "directory error!"
    exit 1
  fi

  echo
  cd $dir; mkdir $TIME; cd $TIME
  echo "Backup............."
  for arr in ${db_names[@]}
  do
    func_mysqldump $arr    
  done 
  echo "Finish"
}

## backup one db user specified
backup_one(){
  # find all db name
  find_db_names
  echo
  echo -e "Please e