对于任何想适当精通一些系统管理知识的人来说,掌握 shell 脚本知识都是最基本的,即使这些人可能并不打算真正的编写一些脚本。
先以三个逐步增强的bash脚本开始系统管理之旅吧,三个程序的基本功能都是清理var/log目录下的messages和wtmp文件中记录的系统消息。
EX_1-1.sh
#Cleanup log files in /var/log
#root permission
cd /var/log
cat /dev/null > messages #clean up message
cat /dev/null > wtmp #clean up wtmp
echo "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/log
cd $LOG_DIR
cat /dev/null > messages
cat /dev/null > wtmp
echo "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/log
ROOT_UID=0
LINES=50
E_XCD=66
E_NOTROOT=67
#root permission
if [ "$UID" -ne "$ROOT_UID" ]
then
echo "Must be root to run this script."
exit $E_NOTROOT
fi
#test command parameter
if [ -n "$1" ]
then
lines=$1
else
lines=$LINES #use default configure if it is not assigned in command
fi
cd $LOG_DIR
#be sure that the current dir is OK before doing with log files.
if [ "$PWD" != "$LOG_DIR" ] #if [ `pwd` != "$LOG_DIR" ]
then
echo "Can't change to $LOG_DIR."
exit $E_XCD
fi
tail messages > mesg.temp #keep the last record message.
mv mesg.temp messages #be a new log file within the last keeped messages
cat /dev/null > wtmp
echo "Logs cleaned up."
exit 0 #return successfully
第三个程序看上去比第一个要大了好多,但可以看出,核心处理代码段是差不多的(有部分改进),之前的一大段代码都是出于安全性、健壮性等,做的各种config、pre-judge。分析问题和实际编码的时候,需要把这些模块区分开,这样可以很容易定位到核心问题,逻辑上也不容易出错。
但不管怎样,可以看出,bash可以写出很精简的代码,去实现很多高级的编译语言需要多出几倍的代码量的功能。这点无疑极具吸引力。