1、需求
线下开发机器数据log表数据增长很快,机器磁盘空间经常满,导致问题,现需要写个crontab脚本定时清理表数据。
2、定时任务添加
crontab -e
*/1 * * * * source /etc/profile; sh /Data/apps/clean_db.sh >> /tmp/crontab.log 2>&1
3、clean_db.sh
#!/bash/bin
# execute sql stat
mysql -h10.1.210.168 -uadmin -pswh123456 -e 'use cachecloud;truncate table standard_statistics'
4、执行报错
/Data/apps/clean_db.sh: line 3: mysql: command not found
解决1:注意是因为crontab环境变量没有导入
*/1 * * * * source /etc/profile; sh /Data/apps/clean_db.sh >> /tmp/crontab.log 2>&1
解决2:shell脚本mysql命令写全路径
5、SQL语句直接嵌入到shell脚本
--演示环境
[root@SZDB ~]# more /etc/issue
CentOS release 5.9 (Final)
Kernel \r on an \m
root@localhost[(none)]> show variables like 'version';
+---------------+------------+
| Variable_name | Value |
+---------------+------------+
| version | 5.6.12-log |
+---------------+------------+
[root@SZDB ~]# more shell_call_sql1.sh
#!/bin/bash
# Define log
TIMESTAMP=`date +%Y%m%d%H%M%S`
LOG=call_sql_${TIMESTAMP}.log
echo "Start execute sql statement at `date`." >>${LOG}
# execute sql stat
mysql -uroot -p123456 -e "
tee /tmp/temp.log
drop database if exists tempdb;
create database tempdb;
use tempdb
create table if not exists tb_tmp(id smallint,val varchar(20));
insert into tb_tmp values (1,'jack'),(2,'robin'),(3,'mark');
select * from tb_tmp;
notee
quit"
echo -e "\n">>${LOG}
echo "below is output result.">>${LOG}
cat /tmp/temp.log>>${LOG}
echo "script executed successful.">>${LOG}
exit;
[root@SZDB ~]# ./shell_call_sql1.sh
Logging to file '/tmp/temp.log'
+------+-------+
| id | val |
+------+-------+
| 1 | jack |
| 2 | robin |
| 3 | mark |
+------+-------+
Outfile disabled.
--Author : Leshami
--Blog : http://blog.csdn.net/leshami
6、清理日志脚本:clean_log.sh
#!/bash/bin
# execute sql stat
for log in `find /Data/apps/ -name '*.log'`
do
`echo '' > $log`
done