Bash编程初步(一)

        对于任何想适当精通一些系统管理知识的人来说,掌握 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可以写出很精简的代码,去实现很多高级的编译语言需要多出几倍的代码量的功能。这点无疑极具吸引力。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值