MySQL历史数据归档以及释放磁盘空间 Shell 脚本

MySQL 历史数据归档脚本,对较久之前的数据进行备份,以释放磁盘空间的压力。清理历史数据表,注意数据无价,将数据备份好的情况下方可执行该脚本。

MySQL 历史数据归档脚本

[root@seichung ] vim /data/sh/history_backup.sh

#!/bin/bash
# By Seichung


# 数据库信息
Dbname='wordpress'
Host='localhost'
User='root'
Password='123456'
Port=3306

# 时间戳
Date=`date +'%Y%m%d%H%M%S'`

# 导出的历史数据表
Tables='/opt/history_tables.txt'

# 查看状态
mysql -h${Host} -u${User} -p${Password} -P ${Port} -e 'use ${Dbname};' &>/dev/null

# 判断该库是否存在
if [ $? = 0 ];then
    echo -e "The database '${Dbname}' is starting, please wait for the backup to finish……"
# 开始进行数据备份
    cat ${Tables} | while read table
    do
# 将同个库中的所有表都备份归档到同一个文件
        mysqldump -h${Host} -u${User} -p${Password} -P ${Port} --set-gtid-purged=OFF --single-transaction --databases ${Dbname} --tables ${table}  >> /data/backup/history_data/${Dbname}-history-data-${Date}.sql 2>/dev/null
    done
    if [ $? = 0 ];then
        echo "Database '${Dbname}' is backup successfully!" 2>/dev/null
    else
        echo "Database '${Dbname}' is backup failed!" 2>/dev/null
    fi
    exit 2
else
    echo "This database '${Dbname}' is not run. Please check it!"
    exit 2
fi

释放磁盘空间

[root@seichung ] vim history_clean.sh

# By Seichung
# 清理历史数据表,注意数据无价,将数据备份好的情况下方可执行该脚本!

# 数据库信息
Dbname='wordpress'
Host='localhost'
User='root'
Password='123456'
Port=3306

# 时间戳
Date=`date +'%Y%m%d%H%M%S'`

# 导出的历史数据表
Tables='/opt/history_tables.txt'

# 查看状态
mysql -h${Host} -u${User} -p${Password} -P ${Port} -e 'use ${Dbname};' &>/dev/null

# 判断该库是否存在
if [ $? = 0 ];then
  echo "The database ${Dbname} is being cleaned up, please wait for it to be cleaned up"  
  # 开始清理
  cat $Tables | while read table
  do
    mysql -h${Host} -u${User} -p${Password} -P ${Port} -e "truncate table ${table};" 2>/dev/null
  echo "The table '${table}' has been cleared"
  done
else
    echo "This database '${Dbname}' is not run. Please check it!"
    exit 2
fi

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值