---
title: "定期清空日志文件"
author: "夜鸣猪"
date: "2012-09-11T10:04:23Z"
tags: []
categories: ["操作系统"]
slug: "untitled"
draft: false
lastmod: "2012-09-11T10:04:23Z"
id: 1675559
url: "https://hlee.iteye.com/blog/1675559"
---

一个关于如何在指定文件大于1GB后，自动删除的问题。
批处理代码如下：

```ruby
#!/bin/bash 
# 当/var/log/syslog大于1GB时 
# 自动将其备份，并清空 
# 注意这里awk的使用 
if ! [ -f /var/log/syslog ] 
then 
echo "file not exist!" 
exit 1 
fi 
if [ `ls -l /var/log/syslog|awk '{print $5}'` -gt $((1024*1024)) ] 
then 
cat /var/log/syslog >> ~/log/history # 将日志备份 
echo >> ~/log/history # 增加一个空行 
date >> ~/log/history # 记录时间 
echo "-------------------------------------" >> ~/log/history 
echo > /var/log/syslog # 清空 
fi
```



Linux系统的日志文件，比如Apache的日志文件，在使用了一段时间后，可能会变得比较大，如果不清空的话，可能会发生这样那样的问题。定期清空一下这些日志文件是比较好的办法。 
　　这里以清空Apache的日志文件为例，我使用的是系统的默认配置，日志的文件在/var/log/httpd下面，访问日志的格式是： 
　　CustomLog logs/access_log combined 
　　生成的访问日志文件类似于：access_log_20101118……，可以使用shell脚本定期删除日志文件，只保留近3天的文件，以免日志文件占满磁盘空间。 
　　建立清除日志文件的shell脚本，文件名为clean_log,存放目录任意 

```ruby
　　#! /bin/bash 
　　logdir=/var/log/httpd 
　　cd ${logdir} 
　　declare -i filesum=`ls access_log_* | wc -l` 
　　declare -i delnum=$filesum-3 
　　if [ "${delnum}" -ge 1 ];then 
　　rm -rf `ls -tr access_log_* | head -${delnum}` 
　　fi 
　　#添加运行权限：chmod 755 clean_log 
　　#再添加为自动运行任务：vi /etc/crontab，添加： 
　　01 04 * * * /root/Desktop/clean_log
```