清除日志文件 初级写法写法很简单,很直观,但是对一些异常做处理。 # Cleanup# Run as root.cd /var/logcat /dev/null > messagescat /dev/null > wtmpecho 'Log files cleaned up.' 改进型写法引入变量,相较于第一种写法,比较规范。
增强通用性版本推荐的一种写法,比较严谨,做了异常处理,更安全。 #!/bin/bashLOG_DIR=/var/logROOT_UID=0 # Only users with $UID 0 have root privileges.LINES=50 # Default number of lines saved.E_XCD=86 # Can't change directory?E_NOTROOT=87 # Non-root exit error.# Run as rootif [ '$UID' -ne '$ROOT_UID' ]then echo 'Must be root to run this script.' exit $E_NOTROOTfi if [ -n '$1' ]# Test whether command-line argument is present (non-empty).then lines=$1else lines=$LINES # Default, if not specified on command-line.fi cd $LOG_DIRif [ `pwd` != '$LOG_DIR' ] # or if [ '$PWD' != '$LOG_DIR' ] # Not in /var/log?then echo 'Can't change to $LOG_DIR.' exit $E_XCDfi # Doublecheck if in right directory before messing with log file.tail -n $lines messages > mesg.temp # Save last section of message log file.mv mesg.temp messages # Rename it as system log file.cat /dev/null > wtmp # ': > wtmp' and '> wtmp' have the same effect.echo 'Log files cleaned up.'exit 0# A zero return value from the script upon exit indicates success#+ to the shell. |
|