Bash编程初步(一)

来源:互联网 发布:百战天虫豪华版java 编辑:程序博客网 时间:2024/04/28 20:04

        对于任何想适当精通一些系统管理知识的人来说,掌握 shell 脚本知识都是最基本的,即使这些人可能并不打算真正的编写一些脚本。

        先以三个逐步增强的bash脚本开始系统管理之旅吧,三个程序的基本功能都是清理var/log目录下的messages和wtmp文件中记录的系统消息。

EX_1-1.sh

#Cleanup log files in /var/log#root permissioncd /var/logcat /dev/null > messages#clean up messagecat /dev/null > wtmp#clean up wtmpecho "Logs cleaned up."


EX_1-2.sh

#!/bin/bash#this is a right head of bash script#root permission#use variable to instead of const#note:1.LOG_DIR is right, $LOG_DIR is wrong.#2.On the left and right position of "=",there is no space strings.LOG_DIR=/var/logcd $LOG_DIRcat /dev/null > messagescat /dev/null > wtmpecho "Logs cleaned up."exit#a right and appropriate way of quit program



EX_1-3.sh      

#!/bin/bash#a strong and broad bash script to clean up log files.LOG_DIR=/var/logROOT_UID=0LINES=50E_XCD=66E_NOTROOT=67#root permissionif [ "$UID" -ne "$ROOT_UID" ]thenecho "Must be root to run this script."exit $E_NOTROOTfi#test command parameterif [ -n "$1" ]thenlines=$1elselines=$LINES#use default configure if it is not assigned in commandficd $LOG_DIR#be sure that the current dir is OK before doing with log files.if [ "$PWD" != "$LOG_DIR" ] #if [ `pwd` != "$LOG_DIR" ]thenecho "Can't change to $LOG_DIR."exit $E_XCDfitail  messages > mesg.temp #keep the last record message.mv mesg.temp messages#be a new log file within the last keeped messagescat /dev/null > wtmpecho "Logs cleaned up."exit 0#return successfully
        第三个程序看上去比第一个要大了好多,但可以看出,核心处理代码段是差不多的(有部分改进),之前的一大段代码都是出于安全性、健壮性等,做的各种config、pre-judge。分析问题和实际编码的时候,需要把这些模块区分开,这样可以很容易定位到核心问题,逻辑上也不容易出错。

        但不管怎样,可以看出,bash可以写出很精简的代码,去实现很多高级的编译语言需要多出几倍的代码量的功能。这点无疑极具吸引力。