一直很喜欢写unix shell script, 因为写那么一点点东西可以有那么多效果,投入小,产出大,爽啊.
在写IBM AIX K Shell script时,感觉不那么友好,主要是有一些格式细节要求比较严格,不太习惯,后来写惯了也就好了,下面的三个script是我为公司最近写的
一个自动备份shell script,基本要求就是每天晚上23:00自动跑起来,看file system
/health used space是否超过了 60%,超过了就压缩三个目录下的 .dat, .log.文件,
压缩方式是gzip(.gz),本来 bzip2(.bz)的压缩率比 .gz要大1.5倍左右, 因为考虑到要 用 zgrep工具直接在文件中search字符串,而且影盘容量足够大,所以也就用gzip了.我自己感觉这三个 k shell script基本上把 aix 的 k shell script的一些特性都覆盖到了,所以就用这个例子, 文本分析我用了awk, 没用 perl,因为用不上perl那些超强的extended regular expression分析,我就用了awk,附件中有个awk文件的例子,awk也可以做比较复杂的分析,但肯定没有perl那样强,主要是perl超级强大的extended regular expression分析. 但是如果你要OOP而且要复杂文本分析,我建议你用perl或者如果你用java你就可以用oro来做perl文本分析,我的一个附件是在java中用oro进行文本分析的代码片段.
先讲一讲 IBM AIX k shell script的一些注意事项吧:
(1) 注意 if 中括号的间距
if [ -d "$HOME/backup" ] , 两边的中扩号和中扩号之间的 condition一定要有空格哦.
(2) 注意在 condition当中数据的等于和字符串的等于可是不一样的偶
if [ $size_out_file_kb -gt 512 ] ;then
cp out.txt out.txt.old
rm out.txt
fi
if [ $(($current_size>=$size_threshold)) -eq 1 ] ;then
print "exceed threshold" >> out.txt
return 1;
else
print " not exceed threshold" >> out.txt
return 0;
fi
if [ $HOST_NAME = "iedm2d24" ] ;then
echo "$file last_modified_time = $last_modif_time" >> out.txt
fi
注意条件中字符串的等于只是一个=,而不是两个=,而且这个=两边还必须和内容有一个空格,是有点变态吧.
(3) 注意 function的返回只能是数值而且返回的数值不能太大
而且会自动进行数据转换,比如你想按照字符串返回 “02”,可是你去读 $? (表示上个 unix命令的返回值,用这种方法去读 function的返回值),结果却自动返回了 2, 说到底是因为 function的返回值也就是 unix中的 exit code,一般用0表示正确返回,当然你在function当中你可以利用 exit code返回 function的返回值.
################################################################################
# description: utility function, transform alphebatic month to digit month
# input parameters:
# $1 Alphabetic month e.g Jan
# return:
# Digith month e.g 1(not 01),2,3,4,5,6,7,8,9,10,11,12
################################################################################
function get_digit_month
{
#print "alphabetic month=" $1 >> out.txt
case $1 in
Jan* )
return "01" ;;
Feb* )
return "02" ;;
Mar )
return "03" ;;
Apr* )
return "04" ;;
May* )
return "05" ;;
Jun* )
return "06" ;;
Jul* )
return "07" ;;
Aug* )
return "08" ;;
Sep* )
return "09" ;;
Oct* )
return "10" ;;
Nov* )
return "11" ;;
Dec* )
return "12" ;;
* )
echo " no a way to find current month "
exit 1 ;;
esac
}
调用function
get_digit_month $alpha_month
echo $? | awk '{if(length($0)==1){print "0"$0}else{print $0}}'| read digit_month
(4) 注意怎样才能给一个数组赋值-用空格分隔的一串数据赋予一个数组
THE_PIDS=`ps -ef |grep "PCRMonitor.pl" |awk '{print $2 " " $3}'`
set -A pids $THE_PIDS
(5) 赋值时等号两边不能有任何空格,有空格就不能赋值了
index_2=0
可不能像在C++当中那样写成 index_2 = 0了.
(6) Local宣称时不能同时赋初值
local last_modif_time
其他的flow control ( if , for, case等),没有什么太需要注意的,可用本例子
直接作参考
因为cdsn的blog不能带附件,所以我用了csdn上传资源的方式,麻烦 J
请在csdn上传资源中查寻
<<包含了几乎所有 unix shell script编程特性的 unix shell script 完整项目, 基于 IBM AIX,附注释.rar>>