分享

Linux 高级Bash脚本实战案例一

 苏醒的贝壳 2023-02-28 发布于北京

清除日志文件

初级写法

写法很简单,很直观,但是对一些异常做处理。

# Cleanup# Run as root.cd /var/logcat /dev/null > messagescat /dev/null > wtmpecho 'Log files cleaned up.'

改进型写法

引入变量,相较于第一种写法,比较规范。

#!/bin/bash# Run as root.LOG_DIR=/var/log# Variables are better than hard-coded values.cd $LOG_DIRcat /dev/null > messagescat /dev/null > wtmpecho 'Logs cleaned up.'exit 

增强通用性版本

推荐的一种写法,比较严谨,做了异常处理,更安全。

#!/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.

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多