数据库自动备份脚本


  1. 脚本mysqlbak.sh

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    #!/bin/bash
    tool=/usr/bin/mysqldump
    dd=`date +%Y%m%d`
    username=root
    password=123456
    database=db
    backup_count=2
    backup_dir=~/mysqlbackup
    # 创建备份目录
    mkdir -p $backup_dir
    #创建备份 mysqldump -u root -p123456 users > /root/mysqlbackup/users-$filename.sql
    $tool -u $username -p$password $database > $backup_dir/$database-$dd.sql
    #写备份日志
    echo "create $backup_dir/$database-$dd.sql" >> $backup_dir/action.log
    #找出需要删除的备份
    delfile=`ls -l -crt $backup_dir/*.sql | awk '{print $9 }' | head -1`
    #判断现在的备份数量是否大于$backup_count
    count=`ls -l -crt $backup_dir/*.sql | awk '{print $9 }' | wc -l`
    if [ $count -gt $backup_count ]
    then
    rm $delfile #删除最早生成的备份,只保留backup_count数量的备份
    #写删除文件日志
    echo "delete $delfile" >> $backup_dir/action.log
    fi
  2. 创建crontab

    1
    2
    3
    #早上5点执行脚本
    crontab -e
    0 5 * * * /absolute/path/to/mysqlbak.sh > /dev/null 2>&1 &

大功告成!