一个很使用的清除日志脚本
精简版
#!/bin/bash // 一个bash脚本的正确的开头部分.
#filename:clean_full_log.sh
#datetime:2010_12_23 11:43
#discription:clean unused log in the directory /var/log
log_dir=/var/log
# 如果使用变量,当然比把代码写死的好.
cd $log_dir
cat /dev/null > messages
cat /dev/null > wtmp
echo "logs cleaned up."
exit # 这个命令是一种正确并且合适的退出脚本的方法.
完整版
#filename:clean_log.sh
#datetime:2010_12_23 15:28
#discription:clean certain of unused log in the directory /var/log
root_uid=0 # $uid为0的时候,用户才具有root用户的权限
lines=50 # 默认的保存行数
e_xcd=66 # 不能修改目录?
e_notroot=67 # 非root用户将以error退出
# 当然要使用root用户来运行.
if [ "$uid" -ne "$root_uid" ]
then
echo "must be root to run this script."
exit $e_notroot
fi
if [ -n "$1" ]
# 测试是否有命令行参数(非空).
lines=$1
else
lines=$lines # 默认,如果不在命令行中指定.
# stephane chazelas 建议使用下边
#
# e_wrongargs=65 # 非数值参数(错误的参数格式)
# case "$1" in
# "" ) lines=50;;
# *[!0-9]*) echo "usage: `basename $0` file-to-cleanup"; exit $e_wrongargs;;
# * ) lines=$1;;
# esac
if [ `pwd` != "$log_dir" ] # 或者 if[ "$pwd" != "$log_dir" ]
# 不在 /var/log中?
echo "can't change to $log_dir."
exit $e_xcd
fi # 在处理log file之前,再确认一遍当前目录是否正确.
# 更有效率的做法是:
# cd /var/log || {
# echo "cannot change to necessary directory." >&2
# exit $e_xcd;
# }
tail -$lines messages > mesg.temp # 保存log file消息的最后部分.
mv mesg.temp messages # 变为新的log目录.
# cat /dev/null > messages
#* 不再需要了,使用上边的方法更安全.
cat /dev/null > wtmp # ': > wtmp' 和 '> wtmp'具有相同的作用
exit 0
# 退出之前返回0,
#+ 返回0表示成功.
如有错误,欢迎指正
作者:czmmiao 原文地址:http://czmmiao.iteye.com/blog/911380