一個很使用的清除日志腳本
精簡版
#!/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