#!/bin/bash
#按年分区,每年的12月份执行该脚本
table=tablexxx
mysql=/usr/local/mysql/bin/mysql
user=xxx
password=xxxx
#MySQL添加分区的时候,不需要指定字段名称
str_0="alter TABLE $table add partition ("
str_1="PARTITION p"
str_2="VALUES LESS THAN (unix_timestamp('"
str_4=") ENGINE = InnoDB);"
str_3="')"
str_all=''
now_month=`date +%m`
i=1
#按年分区
while [ $i -lt 13 ] #一次添加12个分区
do
month=`date -d "-${i} month ago " +%Y%m` #年月,格式如201607
let j=i+1
day=`date -d "-${j} month ago " +%Y-%m`"-01" #年月日,格式如2016-08-01
str_line="${str_0}$str_1${month} $str_2${day}${str_3}$str_4\n"
# echo $str_line
#格式如:alter TABLE tablexxx add partition (PARTITION p201607 VALUES LESS THAN (unix_timestamp('2016-08-01')) ENGINE = InnoDB);
str_all=$str_all${str_line}
let i=i+1
done
#echo -e $str_all
crontab中配置12月执行即可。