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可以写出很精简的代码,去实现很多高级的编译语言需要多出几倍的代码量的功能。这点无疑极具吸引力。
- Bash编程初步(一)
- Bash基本编程(一)
- Bash编程实例 一
- Bash编程实例 一
- bash编程--(一)
- bash编程基础知识(一)
- bash shell 编程练习一
- Bash脚本编程教程(一): Bash脚本编程简介
- Ubuntu编程->bash编程(一)
- 高级BASH 编程 笔记(一)BASH 入门
- bash shell脚本编程学习总结一
- 一图掌握bash shell编程
- bash初步学习笔记
- bash的初步学习
- 网络编程初步认识(一)
- 初步学习网络编程tcp/ip (一)
- bash编程
- bash编程
- 精益生产(Lean manufacturing)
- 如何用C#在Word文档中搜索文本
- 给Tomcat,Apache配置gzip压缩(HTTP压缩)功能
- C#关闭进程树
- googlesitemap
- Bash编程初步(一)
- 2012微软暑期实习生笔试题
- 40处绝胜景点之中国太美
- Ruby元编程(一)
- 学习linux的经典书籍和文献汇总
- 学习OpenCV——SVM 手写数字检测
- ios 开发中对于ipad 和iPhone的判断逻辑 备忘
- MKMapView自定义pin大小不同,位置对齐问题
- Starling 框架帮助手册中文版《一》