• Linux/Centos/Ubuntu crontab备份数据库


    1 前言

    环境:Ubuntu。作为记录使用。

    2 代码

    2.1 脚本样例如下
    # !/bin/sh
    dd="$(date +"%Y%m%d%H%M%S")"
    # 保存备份个数,备份31天数据
    number=31
    # 备份保存路径
    backup_dir=/var/lib/mysql/backup
    # 将要备份的数据库
    database_name=sampleDBName
    # 如果文件夹不存在则创建
    if [ ! -d $backup_dir ];
    then
    mkdir -p $backup_dir;
    fi
    # 执行备份命令
    /usr/bin/mysqldump --defaults-extra-file=/etc/mysql/conf.d/mysql.cnf sampleDBName>$backup_dir/$database_name-$dd.sql
    # 写创建备份日志
    echo "create $backup_dir/$database_name-$dd.dupm" >> $backup_dir/log.txt
    # 找出需要删除的备份
    delfile=`ls -l -crt $backup_dir/*.sql | awk '{print $9 }' | head -1`
    # 判断现在的备份数量是否大于$number
    count=`ls -l -crt $backup_dir/*.sql | awk '{print $9 }' | wc -l`
    if [ $count -gt $number ]
    then
    # 删除最早生成的备份,只保留number数量的备份
    rm $delfile
    # 写删除文件日志
    echo "delete $delfile" >> $backup_dir/log.txt
    fi
    

    2.2 crontab -l查看列表,-e 修改并使之生效

    crontab -l
    # Edit this file to introduce tasks to be run by cron.
    # 
    # Each task to run has to be defined through a single line
    # indicating with different fields when the task will be run
    # and what command to run for the task
    # 
    # To define the time you can provide concrete values for
    # minute (m), hour (h), day of month (dom), month (mon),
    # and day of week (dow) or use '*' in these fields (for 'any').# 
    # Notice that tasks will be started based on the cron's system
    # daemon's notion of time and timezones.
    # 
    # Output of the crontab jobs (including errors) is sent through
    # email to the user the crontab file belongs to (unless redirected).
    # 
    # For example, you can run a backup of all your user accounts
    # at 5 a.m every week with:
    # 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
    # 
    # For more information see the manual pages of crontab(5) and cron(8)
    # 
    # m h  dom mon dow   command
    0 1 * * * /bin/sh /var/lib/mysql/sh/dbBackup.sh
    说明:代表每一天01:00分执行

    3 结束语

  • 相关阅读:
    人在年轻的时候,最需要的能力--吃药的能力
    查分单词-Python
    关于NLP算法工程师的几点思考
    找出只出现一次的数字-Python
    最长连续序列
    二叉树中的最大路径和-Python
    windows:查找端口所对应的进程
    vue项目路由模式为history时打包后部署在nginx 配置访问
    用navicat连接数据库报错:1130-host ... is not allowed to connect to this MySql server如何处理
    mysql误删root用户
  • 原文地址:https://www.cnblogs.com/fanbi/p/15305322.html
Copyright © 2020-2023  润新知