Linux shell脚本-删除数据库当天日期前3个月的所有表数据
使用mysql_config_editor可以实现将密码保存在一个配置中,下次登录不用输入用户名密码,避免出现:
Warning: Using a password on the command line interface can be insecure.
mysql_config_editor set --login-path=test --host=127.0.0.1 --user=root --password
Enter password: (输入密码)
mysql_config_editor print --all #显示所有的login-path信息
mysql_config_editor remove --login-path=test #删除配置
vim del_table.sh
#! /bin/bash
#数据库名
dbName="test"
#数据库时间字段
dbTime="time"
#获取前3个月的日期,格式:2022-3-25
months_ago=`date -d "-3 month" +"%Y"/"%-m"/"%d"`
#查询并生成要清空表的命令
cmd=$(mysql --login-path=${dbName} -e "SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA='$dbName'")
#echo "$cmd"
#循环删除每个表中3个月前的数据
for db in $cmd
do
mysql --login-path=${dbName} -e "use ${dbName}; delete from ${db} where ${dbTime} <= '$months_ago'";
done