很实用的Shell脚本(实践版)
shell脚本案例
shell脚本案例Shell脚本是将一系列的命令写入脚本文件中,让其运行时具备特定的功能。
Shell脚本的一大优势是可以实现一步操作多项任务,在繁重的日常任务管理与网络管理领域中都有着广泛的应用。
本文将着重介绍几个常见的Shell脚本案例,让读者了解有关Shell脚本的实际操作方法。
第一个脚本是批量更改文件所有者及所有组的脚本,代码如下: #!/bin/bashfiles=`ls -A`user=usernamegroup=groupnamefor file in $files; dochown $user:$group $filedone这个脚本首先列出当前工作目录下的文件,并将所有者及所有组设置为指定的两个用户,最后应用chown命令将文件的所有者和所有组都更改为给定的用户及组。
第二个脚本是用来实现文件/文件夹的备份的脚本,代码如下: #! /bin/bashsrcdir=/srcdirbackdir=/backdirmkdir -p $backdircp -R $srcdir/* $backdir这个脚本将指定的源文件夹srcdir的所有内容复制到一个备份文件夹backdir中,确保原文件的完整性。
第三个脚本是用来批量修改文件权限的,代码如下:#! /bin/bashfiles=`ls -A`for file in $files; dochmod -R 755 $filedone这个脚本将当前工作目录下的所有文件/文件夹的可读写权限设置为755,755权限可让所有者及同一组用户可以具有执行及读写权限,而其他用户只有可以读取权限。
以上三个案例展示了Shell脚本的强大功能,能够帮助用户快速完成一系列的工作,避免执行重复的操作,非常适合用作日常任务的自动化管理。
Shell脚本操作简单,编写起来也比较简单,学习它也并不困难,只要用户掌握一定的shell基础知识就可以编写出非常强大的脚本文件。
此外,Shell脚本还可以通过cron计划任务实现定时执行操作,能够有效的节省用户的时间。
30个关于Shell脚本的经典案例(下)
初次使用你要注意这几点:
脚本位置参数会与optstring中的单个字母逐个匹配,如果匹配到就赋值给name,否则赋值name为问号;
optstring中单个字母是一个选项,如果字母后面加冒号,表示该选项后面带参数,参数值并会赋冒号,表示屏蔽系统错误(test.sh: illegal option -- h);
允许把选项放一起,例如-ab
下面写一个打印文件指定行的简单例子,引导你思路:
#!/bin/bash
while getopts :f:n: option; do
case $option in
f)
FILE=$OPTARG
[ ! -f $FILE ] && echo "$FILE File not exist!" && exit
\"(yes/no)\" {send \"yes\r\"; exp_continue} \"password:\" {send \"$PASS\r\"; exp_continue} \"$USER@*\" {send \"df -h\r exit\r\"; exp_continue} }" 方法3:将expect脚本独立出来
Linux shell编程实验作业(含答案)
Linux shell实验作业参考1.编写一个Shell脚本,实现输入一个数字,输出该数字的阶乘。
思路:使用for循环,从1到输入的数字进行累乘,最终输出结果。
#!/bin/bashecho "请输入一个数字:"read numfact=1for ((i=1;i<=$num;i++))dofact=$(($fact*$i))doneecho "阶乘为:$fact"2. 编写一个Shell脚本,实现输入一个目录,输出该目录下所有文件名和文件大小。
#!/bin/bash# 获取目录路径read -p "请输入目录路径:" dir_path# 判断目录是否存在if [ ! -d "$dir_path" ]; thenecho "目录不存在!"exit 1fi# 遍历目录下所有文件for file in "$dir_path"/*do# 判断是否是文件if [ -f "$file" ]; then# 获取文件名和大小file_name=$(basename "$file")file_size=$(du -h "$file" | awk '{print $1}')echo "$file_name : $file_size"fidone使用方法:➢将以上代码保存为一个.sh文件,例如:`list_files.sh`➢给该文件添加执行权限:`chmod +x list_files.sh`➢在终端中运行该脚本:`./list_files.sh`,然后输入目录路径即可。
3. 编写一个Shell脚本,实现输入一个字符串,输出该字符串中所有大写字母的个数。
脚本的基本思路是遍历输入的字符串,对于每个字符,判断是否为大写字母,如果是则计数器加一。
编写高效的Shell脚本的技巧与实例
编写高效的Shell脚本的技巧与实例引言:Shell脚本是自动化执行一系列命令的脚本语言,它在操作系统中扮演着重要的角色。
编写高效的Shell脚本可以提高工作效率和生产力。
本文将介绍一些编写高效Shell脚本的技巧,并提供一些实例来加深理解。
一、选择合适的Shell解释器Shell脚本可以使用多种Shell解释器,如Bash、Zsh、Csh等。
选择合适的Shell解释器可以根据实际需求和环境来进行,一般来说,Bash是使用最广泛的Shell解释器。
二、规范命名和注释命名和注释是编写可读性强的Shell脚本的基础。
为了提高可读性,应使用有意义的变量名、函数名和文件名,并在需要的地方添加注释,以便其他人能够更容易地理解脚本的用途和实现方式。
三、使用合适的命令和参数Shell脚本可以调用系统中的各种命令,为了编写高效的脚本,应使用合适的命令和参数。
例如,对于文件操作,应使用适当的命令,如cp、mv和rm,而不是使用比如cat和grep来实现类似的功能。
四、使用变量和函数变量和函数是Shell脚本中非常重要的组成部分,它们可以帮助提高脚本的可维护性和可扩展性。
合理使用变量和函数可以使脚本更加灵活,易于调试和修改。
实例1:计算文件行数#!/bin/bashfile="/path/to/file.txt"lines=$(wc -l < $file)echo "文件 $file 的行数为 $lines"实例2:批量重命名文件#!/bin/bashprefix="new_"for file in /path/to/files/*; doif [ -f "$file" ]; thennew_name=${file##*/}new_name="$prefix$new_name"mv "$file" "/path/to/files/$new_name"fidone五、合理使用循环和条件语句循环和条件语句在Shell脚本中起着重要的作用。
【学习】LinuxShell脚本实例之一
【学习】LinuxShell脚本实例之⼀1.程序流程控制实例程序流程控制,实际上就是改变程序的执⾏顺序。
程序在执⾏过程中若流程被改变,就可能导致输出不同,因此利⽤这⼀特性就能够实现程序执⾏结果的控制。
程序流程控制可分为“选择”和“循环”这两类,在需要根据实际需求的不同实现不同的输出时,就可以改变程序的执⾏流程。
(1)for循环语句基于for语句的循环,基于继续执⾏循环或者结束循环的⽅式。
在for执⾏命令前,其会先检查所要执⾏的列表中所指定的值是否还有未使⽤的,若有未使⽤的就赋值并执⾏列表,直到列表中的值全部都使⽤过后才退出循环。
如下是⼀个简单的 for 控制语句的脚本程序,其使⽤“星期”作为变量名,并从列表中读取值,直到读取完成后退出。
我们执⾏⼀下说明:第03 ⾏,所定义的变量名为week,其值为Monday~ Sunday。
第05⾏,使⽤echo回显变量week的值。
(2)while循环语句while循环语句结构是⼀种执⾏⼀系列命令的语句结构,它所执⾏的命令由测试条件所决定,这些条件定义语句是否继续执⾏。
在 while 循环语句中执⾏命令,若条件为真,则将过程执⾏⼀遍并回到开始处,接着再次进⾏条件的判断,若条件仍然是真,则接着再执⾏⼀遍,直到条件为假时才退出循环。
如下是⼀个数值运算的while循环脚本,其实现的是数值相加运算。
执⾏⼀下看⼀下结果说明:第03和04⾏,声明x和sum都为整型变量并赋予初始值。
第05⾏,条件测试。
第06~09⾏,这是⼀个循环体,当执⾏遇到done后,跳到第06⾏处继续执⾏,直到条件不满⾜时退出循环。
第10⾏,输出总数值。
(3)until循环语句与for和while循环体⼀样,until循环也执⾏⼀系列的命令,直到条件满⾜后退出循环。
until循环在循环体的顶部继续判断条件,直到条件为真时结束循环,否则⼀直执⾏。
以下脚本使⽤until语句来实现⼀个简单的、不断循环的输出预设值,直到⼈为⼲预时结束循环(按Ctrl+C组合键退出)。
shell脚本100例、练习使用
shell脚本100例、练习使⽤1、编写hello world脚本#!/bin/bashecho"hello world"2、通过位置变量创建linux系统账户和密码#!/bin/bash#$1是执⾏脚本第⼀个参数 $2是执⾏脚本第⼆个参数useradd "$1"echo"$2" | passwd --stdin "$1"#测试脚本[root@template-host sh1]# sh2.sh aaa 123Changing password for user aaa.passwd: all authentication tokens updated successfully.#测试登录[root@template-host sh1]# su - aaa[aaa@template-host ~]$3、每周五使⽤tar命令备份 /var/log下的所有⽇志⽂件#!/bin/bashtar -czPf log-`date +%y%m%d`.tar.gz /var/log #加P是因为如果不加会出现错误:tar: Removing leading `/' from member names date和+之间注意有空格。
修改系统参数[root@template-host sh1]# crontab -e00 03 * * 5 /data/sh1/3.sh4、⼀键部署LNMP(RPM包版本)#!/bin/bash#此脚本需要提前配置yum源,否则⽆法配置成功。
本脚本使⽤于7.4yum -y install httpdyum -y install mariadb mariadb-devel mariadb-serveryum -y install php php-mysqlsystemctl start httpd mariadb #启动httpd、mariadbsystemctl enable httpd mariadb #加⼊开机⾃启动systemctl status httpd mariadb #查看是否成功5、实时监控本机硬盘内存剩余空间,剩余内存空间⼩于500M,根分区剩余空间⼩于1000M时,发送警报信息到命令⾏#!bin/bash#提取分区剩余空间单位:kbdisk_size=$(df / | awk'/\//{print $4}')#提取内存空间单位Mmem_size=$(free -m | awk'/Mem/{print $4}')while :doif [ $disk_size -le 512000 -o $mem_size -le 1024 ];thenecho"警报:资源不⾜"sleep5fidone6、随机⽣成⼀个100以内的随机数,提⽰⽤户猜数字,提⽰⽤户猜⼤了、猜⼩了、猜对了,直⾄⽤户猜对,脚本结束。
如何编写可维护的Shell脚本高级技巧和最佳实践
如何编写可维护的Shell脚本高级技巧和最佳实践Shell脚本是用于与操作系统进行交互的脚本语言,广泛应用于自动化任务、系统管理和软件开发等领域。
编写可维护的Shell脚本是提高开发效率、降低维护成本的重要任务。
本文将介绍一些Shell脚本的高级技巧和最佳实践,帮助您编写出结构清晰、可读性强、易于维护的Shell脚本。
一、使用可靠的Shell解释器选择合适的Shell解释器是编写可维护Shell脚本的第一步。
常见的Shell解释器包括Bash、Zsh和Fish等,其中Bash是最常用的Shell解释器。
确保在脚本的开头使用正确的解释器声明,例如:#!/bin/bash二、设置合适的选项设置合适的选项可以帮助您避免一些常见的错误,并改善脚本的健壮性和可移植性。
以下是一些常用的选项设置:set -o errexit # 如果任何命令的退出状态非零,则立即退出脚本set -o nounset # 当使用未初始化的变量时,立即退出脚本set -o pipefail # 如果管道中的任何命令失败,则将整个管道标记为失败三、注释和文档化良好的注释和文档化是编写可维护Shell脚本的关键。
通过清晰的注释和文档,可以使其他开发人员更容易理解和维护您的脚本。
以下是一些建议:- 在脚本的开头添加版权声明和摘要,描述脚本的用途和功能。
- 在每个函数的开头添加注释,说明函数的作用和参数。
- 对于复杂的逻辑或算法,使用注释来解释算法的思路和实现方法。
四、错误处理合适的错误处理可以提高脚本的健壮性和可维护性。
以下是一些建议:- 使用函数来封装重复的错误处理代码,提高代码的复用性。
- 在关键的错误处理点处添加必要的日志记录,以便更好地排查问题。
- 使用适当的返回值和退出码来指示脚本的状态。
五、变量和参数处理合理使用变量和参数可以使脚本更具可读性和灵活性。
以下是一些建议:- 使用有意义的变量名,提高代码的可读性和可维护性。
- 使用参数来传递脚本的输入,使脚本更具通用性。
shell脚本案例
shell脚本案例1.设计⼀个shell程序,添加组为class1,然后添加属于这个组的30个⽤户,⽤户名为 stuxx,其中xx从01到 30#!/bin/bashi=1groupadd class1while [ $i -le 30 ]doif [ $i -le 9 ];thenUSERNAME=stu0${i}elseUSERNAME=stu${i}fiuseradd $USERNAMEmkdir /home/$USERNAMEchown -R $USERNAME /home/$USERNAMEchgrp -R class1 /home/$USERNAMEi=$(($i+1))done2.编写⼀个shell程序,实现⾃动删除30个账号的功能,账户名为stu01⾄stu30#!/bin/bashi=1while [ $i -le 50 ]doif [ $i -le 9 ];thenname=stu0$ielsename=stu$ifiuserdel -r $namei=$(($i+1))done3.设计⼀个shell程序,在每⽉第⼀天备份并压缩/etc⽬录的所有内容,存放在 /root/back⽬录⾥,且⽂件名未如下命名格式,yy为年mm为⽉,dd为⽇。
shell程序fileback存放在/usr/bin⽬录下。
(1)编写shellx程序fileback#!/bin/bashDIRNAME=`ls /root/back`if [ $? -eq 0 ];thensleep 3exit 1elsemkdir /root/backcd /root/backYY=`date +%y`MM=`date +%m`DD=`date +%d`BACKETC=$YY$MM$DD_etc.tar.gztar zcvf $BACKETC /etc/echo "fileback finished"fi(2)编写定时任务echo "0 0 1 * * /bin/sh /usr/bin/fileback" > /root/etc_backcrontab /root/etc_back或者使⽤crontab -e添加定时任务0 0 1 * * /bin/sh /usr/bin/fileback3.设计⼀个shell程序,在/userdate⽬录下创建50个⽬录,即user1-user20,并设置每个⽬录的权限,其他⽤户的权限为:读,⽂件所有者的权限为:读,写执⾏,⽂件所有者所在的组的权限为:读,执⾏。
很实用的Shell脚本(实践版)
ApacheLogRotate.shecho`date`":Clean the apache logs">/usr/WebSphere/IHS/logs/access_log>/usr/WebSphere/IHS/logs/error_logapforwinbk.shexport DayOfWeek=`date+"%u"`cd/wasbackupcp-rf./WASBackup_"$DayOfWeek".tar./apbkarchiveOld.shexport TargetDir=/erpHome/jln.ear/erp.war/$1/$2export TT=`date+"%Y%m%d"`export DayOfWeek=`date+"%u"`if(test-e$TargetDir)thenmkdir-p/erpHome/shell/old/$1cd$TargetDir#zip-qm/erpHome/old/$1/$2_$TT.zip`find.-mtime+7|awk'{print$0}'` mv/erpHome/shell/old/$1/$2_$DayOfWeek.zip/erpHome/shell/old/$1/$2.zip.oldfind.-mtime+7|xargs nice-n20zip-qm /erpHome/shell/old/$1/$2_$DayOfWeek.zip#find.-mtime+7FiarchiveOld2.sh./erpHome/shell/setP.shexport DayOfWeek=`date+"%u"`if test"$#"-lt1||test-z"$1"thenecho At least one argument needed.exitfiif test!-e"$ShellHome/old/$1"thencd$ShellHome/old/mkdir-p$1fiif test!-e"$ERPHome/$1"thenecho"$ERPHome/$1""does not exist"exitficd$ERPHome/$1mv$ShellHome/old/$1_$DayOfWeek.zip$ShellHome/old/$1.zip.oldfind.-mtime+7-type f|xargs nice-n20zip-qm$ShellHome/old/$1_$DayOfWeek.zip #find.-mtime+7-type farchiveOldAll.sh/erpHome/shell/archiveOld.sh work/dr/engine jrprint/erpHome/shell/archiveOld.sh work/de tmp/erpHome/shell/archiveOld2.sh publicbackupLog.shecho`date`":Backup the logs"./erpHome/shell/setP.shcd$ERPHome/waslogsmkdir old/mv std*_*.txt old/mv$LOGHome/LOG_$DD.zip$LOGHome/LOG.zip.oldzip-qmr$LOGHome/LOG_$DD.zip`ls$ERPHome/waslogs|grep-Ev"std|FATAL_DEBUG.xml"` ls-l$LOGHome/LOG_$DD.zipecho`date`":Backup the logs done."backupWASAll.sh./erpHome/shell/setP.shcd/erpHome#rename old backup fileecho"####"`date`"ERP program backup####"#mv/wasbackup/WASBackup_"$DayOfWeek".tar/wasbackup/WASBackup_old.tarrm-Rf/wasbackup/erpbak/WASBackup_"$DayOfWeek".tar#backup ERP programnice-n20tar-cf/wasbackup/erpbak/WASBackup_"$DayOfWeek".tar jln.ear/erp.war DIClient DIServer ThreadPool erpdatals-l/wasbackup/erpbak/WASBackup_"$DayOfWeek".tarcollectAudit.sh./erpHome/shell/setP.sh jlnaudit shutdownauditpr-v</audit/trail|grep PROC_Execute>$LOGHome/AUDIT_$YYMMDD.txtmv/audit/trail$LOGHome/trail_$TTgzip$LOGHome/trail_$TTaudit startlast|grep"$TT2">$LOGHome/LOGIN_$YYMMDD.txtgrep"$TT3"/var/adm/sulog>$LOGHome/SU_$YYMMDD.txtcplogs.shexport dd=`perl-e'@y=localtime(time()-86400);printf"%02d\n",$y[3];'`cd/erpHome/shell/logsmkdir/test/erplogscp./LOG_"$dd".zip/test/erplogscpnmon.shcd/worktmp/nmonexport dd=`perl-e'@y=localtime(time()-86400);printf"%02d\n",$y[3];'` export d=`date+%y%m`"$dd"export HOSTNAME=`hostname`export data="$HOSTNAME"_"$d"_"*"ftp-n<<EOFopen10.32.1.138user nmon nmoncd$HOSTNAMEput$databyeEOFddd.shcd$1touch11.txtfilter.awkBEGIN{DiscardURLs="/erp/de/deCommand/erp/jsp/"DiscardAmount=split(DiscardURLs,DiscardURL,"")ResponseThreshold=4.9999nlines=0totalCount=0}function extractTime(myDate,aSize){if(aSize==2)return myDate[2]if(myDate[2]=="上午")return myDate[3]split(myDate[3],dates,":")return dates[1]+12":"dates[2]":"dates[3]}function isSkip(myURL){for(i=1;i<=DiscardAmount;i++)if(index(myURL,DiscardURL[i])>0)return1return0}{if(isSkip($3)==0){if(NF==10){totalCount++;if($4>ResponseThreshold){mySize=split($2,myDate,"")myTime=extractTime(myDate,mySize)print$1"\t"myTime"\t"$3"\t"$4"\t"$5"\t"$6nlines++}}}}END{print"本日网页执行总次数:"totalCount"(JSP,servlet,但不包含图片等静态网页,也不包含/erp/jsp/开头的这些监控画面)"print"共"nlines"笔异常资料"formatHTML.awkBEGIN{}function getSysName(myURL){fCount=split(myURL,myArray,"/")return myArray[3]}function getMaxInArray(oArray,oResult,oIndex){maxValue=0for(idx in oCount){if(oCount[idx]>maxValue){maxValue=oCount[idx]maxSys=idx}}delete oArray[maxSys]oResult[oIndex,1]=maxSysoResult[oIndex,2]=maxValue}function sort(array,result,thresHold){for(i=1;i<=5;i++){getMaxInArray(array,result,i)}}{oSys=getSysName($3)if(NF!=6){print$0"<br/>"}else{oCount[oSys]++oRecord++;print"<tr style='background-color:#C4DAFF'><td>"$1"</td><td>"$2 "</td><td>"$3"</td><td>"$4"</td><td>"$5"</td><td>"$6"</td></tr>"}}END{oThreshold oRecord/10sort(oCount,oResult,oThreshold)print"</table>"print"<script>"max=oResult[1,2]for(i=1;i<=5;i++){print"addData(\""(oResult[i,2]/max*100)"pt\","i",\""oResult[i,1]"\",\"" oResult[i,2]"\")"}}formatHTML.awk.oldBEGIN{print"<html><head><meta http-equiv='Content-Type'content='text/html; charset=GBK'><style>td{border:1px solid black;}</style></head><body><H1align>执行时间超过60秒的网址</H1><table style='border:1px solid black'cellspacing=0align=center>"}{if(NF!=6){print$0"<br/>"}else if(NR==1){print"<tr style='background-color:pink'align=center><td>"$1"</td><td>" $2"</td><td>"$3"</td><td>"$4"</td><td>"$5"</td><td>"$6"</td></tr>"}else{print"<tr style='background-color:#C4DAFF'><td>"$1"</td><td>"$2 "</td><td>"$3"</td><td>"$4"</td><td>"$5"</td><td>"$6"</td></tr>"}}END{print"</table></body></html>"}htmlFoot.txt</script></body></html>htmlHead.txt<html><head><meta http-equiv='Content-Type'content='text/html;charset=GBK'><style>@import"/erp/html/dn/filtergrid.css";.td2{border:0px}.td3{border-right}.div1{border:solid black1px}.div2{border:solid black1px;text-align:right}.div3{border:solid1px white}td{border:1px solid black;}</style><script language="javascript"type="text/javascript"src="/erp/html/dn/actb.js"></script><!--External script--><script language="javascript"type="text/javascript" src="/erp/html/dn/tablefilter.js"></script><script language="javascript"type="text/javascript">function doFilter(){var props={remember_grid_values:true,alternate_rows:true,rows_counter:true,rows_counter_text:"Displayed rows:",btn_reset:true,btn_reset_text:"Clear",btn_text:">",loader:true,loader_text:"Filtering data...",col_0:"select",col_1:"none",col_3:"none",col_4:"none",col_5:"select",display_all_text:"<Show all>",sort_select:true}setFilterGrid("table1",props);}</script><script>var Colors=new Array("green","red","blue","yellow","orange")function addData(oWidth,oIndex,oSys,oData){chartBlock.innerHTML+="<div class=div3style='background-color:"+ Colors[(oIndex%5)]+";width="+oWidth+"'></div>";sysBlock.innerHTML+="<div class='div1'>"+oSys+"</div>";dataBlock.innerHTML+="<div class='div2'>"+oData+"</div>";}function doVisible(){if(vf1.innerText=="+"){vf1.innerText="-";chartBlock.style.visibility="visible";sysBlock.style.visibility="visible";dataBlock.style.visibility="visible";}else{vf1.innerText="+";chartBlock.style.visibility="hidden";sysBlock.style.visibility="hidden";dataBlock.style.visibility="hidden";}}</script></head><body><TABLE cellspacing=0cellpadding=0><TR><TD width=100%class=td2><H1align>执行时间超过5秒的网址</H1></TD><div id=myChart style="border:black solid1px"><TD class=td3id=chartBlock style="visibility:hidden"></TD><TD class=td2id=sysBlock style="visibility:hidden"></TD><TD class=td2id=dataBlock style="visibility:hidden"><td id=vf1UNSELECTABLE=on style="cursor:hand"onclick="doVisible()">+</td></div></TD></TR></TABLE><BUTTON UNSELECTABLE=on style="cursor:hand"onclick="doFilter()">Filter</BUTTON><table id=table1style='border:1px solid black'cellspacing=0align=center><tr style='background-color:pink'align=center><td>来源电脑</td><td>时间</td><td>网址</td><td>执行时间</td><td>QueryString</td><td>UserID</td></tr>increaseERP.sh./erpHome/shell/setP.shcd/erpHomefind jln.ear-type f-mtime2-print>/tmp/filelist.txtfind erpdata-type f-mtime2-print>>/tmp/filelist.txttar cvfL/wasbackup/WASBackup_"$DayOfWeek".tar/tmp/filelist.txtnight.old./erpHome/shell/setP.sh$ShellHome/backupLog.sh>>$NightLog2>&1$ShellHome/ApacheLogRotate.sh>>$NightLog2>&1mv/erpHome/bx.ear/erp.war/access.txt/erpHome/shell/logs/access_$YYMMDD.txtawk-F"\t"-f/erpHome/shell/filter.awk/erpHome/shell/logs/access_$YYMMDD.txt> /erpHome/shell/logs/temp.csv#echo"ㄓ方筿福, 丁,呼,磅︽ 丁,QueryString,UserID">/erpHome/shell/logs/temp2.csv echo"来源电脑,时间,网址,执行时间,QueryString,UserID">/erpHome/shell/logs/temp2.csv sort-t","+3-n-r/erpHome/shell/logs/temp.csv>>/erpHome/shell/logs/temp2.csvawk-F","-f/erpHome/shell/formatHTML.awk/erpHome/shell/logs/temp2.csv> $ERPHome/public/$YYMMDD.htmlgzip-v/erpHome/shell/logs/access_$YYMMDD.txt>>$NightLog2>&1sv#awk-f/erpHome/shell/filter.awk/erpHome/shell/logs/access_$YYMMDD.txt> $ERPHome/public/$YYMMDD.html#gzip-v/erpHome/shell/logs/access_$YYMMDD.txt>>$NightLog2>&1night.sh./erpHome/shell/setP.sh#/usr/WebSphere/AppServer/bin/stopServer.sh server1>>$NightLog2>&1$ShellHome/backupLog.sh>>$NightLog2>&1$ShellHome/ApacheLogRotate.sh>>$NightLog2>&1#$ShellHome/processFile.sh db_serv20000>>$NightLog2>&1#mv$ERPHome/access.txt/erpHome/shell/logs/access_$YYMMDD.txtawk-F"\t"-f/erpHome/shell/filter.awk/erpHome/shell/logs/access_$YYMMDD.txt> /erpHome/shell/logs/temp.csvsort+3-n-r/erpHome/shell/logs/temp.csv>/erpHome/shell/logs/temp2.csvcat/erpHome/shell/htmlHead.txt>$ERPHome/public/$YYMMDD.htmlawk-F"\t"-f/erpHome/shell/formatHTML.awk/erpHome/shell/logs/temp2.csv>> $ERPHome/public/$YYMMDD.htmlcat/erpHome/shell/htmlFoot.txt>>$ERPHome/public/$YYMMDD.html#gzip-v/erpHome/shell/logs/access_$YYMMDD.txt>>$NightLog2>&1/erpHome/shell/archiveOldAll.sh>>$NightLog2>&1#/usr/WebSphere/AppServer/bin/startServer.sh server1>>$NightLog2>&1night.sh.bak./erpHome/shell/setP.sh#/usr/WebSphere/AppServer/bin/stopServer.sh server1>>$NightLog2>&1$ShellHome/backupLog.sh>>$NightLog2>&1$ShellHome/ApacheLogRotate.sh>>$NightLog2>&1#$ShellHome/processFile.sh db_serv20000>>$NightLog2>&1#mv$ERPHome/access.txt/erpHome/shell/logs/access_$YYMMDD.txt#awk-F"\t"-f/erpHome/shell/filter.awk/erpHome/shell/logs/access_$YYMMDD.txt> /erpHome/shell/logs/temp.csv#sort+3-n-r/erpHome/shell/logs/temp.csv>/erpHome/shell/logs/temp2.csv#cat/erpHome/shell/htmlHead.txt>$ERPHome/public/$YYMMDD.html#awk-F"\t"-f/erpHome/shell/formatHTML.awk/erpHome/shell/logs/temp2.csv>> $ERPHome/public/$YYMMDD.html#cat/erpHome/shell/htmlFoot.txt>>$ERPHome/public/$YYMMDD.htmlgzip-v/erpHome/shell/logs/access_$YYMMDD.txt>>$NightLog2>&1/erpHome/shell/archiveOldAll.sh>>$NightLog2>&1#/usr/WebSphere/AppServer/bin/startServer.sh server1>>$NightLog2>&1#Old.馵..@public!IHS.old.zip'public.zip.old#public_5.zip$public_7.zip*public_1.zip%public_2.zip&pu blic_4.zip(public_6.zip)shell_test.zipwork"public_3.zipxjh@p55013:/erpHome/shell#processFile.shexport YYMM=`/usr/bin/date+"%y%m"`;export YYMMexport YYMMDD=`/usr/bin/date+"%y%m%d"`;export YYMMDDmkdir-p/nmon/report/$1/$YYMM/$YYMMDD/cd/nmonnice-n20./nmon2rrd-f$1_"$YYMMDD"_$2.nmon-d/nmon/report/$1/$YYMM/$YYMMDD -xgzip-9/nmon/report/$1/$YYMM/$YYMMDD/*rrd*gzip-9$1_"$YYMMDD"_$2.nmonres.sh/erpHome/shell/stopServer.sh$1/erpHome/shell/startServer.sh$1restartjvm.sh/usr/WebSphere/AppServer/profiles/AppSrv01/bin/stopServer.sh s1 /usr/WebSphere/AppServer/profiles/AppSrv01/bin/startServer.sh s1 #/usr/WebSphere/AppServer/profiles/AppSrv01/bin/stopServer.sh s2 #/usr/WebSphere/AppServer/profiles/AppSrv01/bin/startServer.sh s2 rmGClog.shcd/usr/WebSphere/AppServer/profiles/AppSrv01/logs/s1>native_stderr.logcd/usr/WebSphere/AppServer/profiles/AppSrv01/logs/s2>native_stderr.logcd/usr/WebSphere/AppServer/profiles/AppSrv01/logs/t1>native_stderr.logcd/usr/WebSphere/AppServer/profiles/AppSrv01/logs/t2rmwasbackup.shcd/wasbackupfind.-ctime+1-exec rm{}\;server.lstserver1setP.shexport ERPHome=/erpHome/jln.ear/erp.warif!test-e$ERPHomethenecho"Warning!"$ERPHome"not exists."exitfiexport ShellHome=/erpHome/shellexport LOGHome=/erpHome/shell/logsexport WAS_HOME=/usr/WebSphere/AppServerexport Java_Home=$WAS_HOME/java/export TT=`date+"%Y%m%d%H%M%S"`export TT2=`date+"%b%d"`export TT3=`date+"%m/%d"`export YYMMDD=`date+"%Y%m%d"`export DD=`date+"%d"`export UpdateLog=$LOGHome/update_$YYMMDD.txt export NightLog=$LOGHome/night_$YYMMDD.txtexport DayOfWeek=`date+"%u"`startAllService.sh/usr/WebSphere/IHS/bin/apachectl start/erpHome/ThreadPool/bin/go.sh start/erpHome/DIServer/bin/go.sh start/usr/WebSphere/AppServer/bin/startServer.sh server1startServer.sh#!/usr/bin/kshif test"$#"-lt1||test-z"$1"thenecho Usage:$0[ServerName]echo"Available ServerName:"awk'{print"\t\t\t"$1}'/erpHome/shell/server.lstexitfiIFSsave=$IFSwhile IFS='';read linedoif test$1=$linethenexport ValidArg=1breakfidone</erpHome/shell/server.lstIFS=$IFSsaveif test-z"$ValidArg"thenecho Invalid ServerName.echo"Available ServerName:"awk'{print"\t\t\t"$1}'/erpHome/shell/server.lstexitfiexport ServerName=$1echo"####################start$1`date`####################">> /erpHome/shell/logs/serverRestart.log/usr/WebSphere/AppServer/bin/startServer.sh$1stopServer.sh#!/usr/bin/kshif test"$#"-lt1||test-z"$1"thenecho Usage:$0[ServerName]echo"Available ServerName:"awk'{print"\t\t\t"$1}'/erpHome/shell/server.lstexitfiIFSsave=$IFSwhile IFS='';read linedoif test$1=$linethenexport ValidArg=1breakfidone</erpHome/shell/server.lstIFS=$IFSsaveif test-z"$ValidArg"thenecho Invalid ServerName.echo"Available ServerName:"awk'{print"\t\t\t"$1}'/erpHome/shell/server.lstexitfiexport ServerName=$1echo"####################stop$1`date`####################">> /erpHome/shell/logs/serverRestart.log/usr/WebSphere/AppServer/bin/stopServer.sh$1syncConfig.shcp/erpHome/jln.ear/erp.war/WEB-INF/web.xml/usr/WebSphere/AppServer/profiles/Dmgr01/config/cells/p55013Cell01/applications/jln.ear/ deployments/jln/erp.war/WEB-INFcp/erpHome/jln.ear/erp.war/WEB-INF/web.xml/usr/WebSphere/AppServer/profiles/AppSrv01/config/cells/p55013Cell01/applications/jln.ear /deployments/jln/erp.war/WEB-INF/usr/WebSphere/AppServer/profiles/Dmgr01/bin/GenPluginCfg.shsyncConfig.sh.bakcp/erpHome/jln.ear/erp.war/WEB-INF/web.xml/usr/WebSphere/AppServer/profiles/Dmgr01/config/cells/p510Cell01/applications/jln.ear/de ployments/jln/erp.war/WEB-INFcp/erpHome/jln.ear/erp.war/WEB-INF/web.xml/usr/WebSphere/AppServer/profiles/AppSrv01/config/cells/p510Cell01/applications/jln.ear/d eployments/jln/erp.war/WEB-INF/usr/WebSphere/AppServer/profiles/Dmgr01/bin/GenPluginCfg.shupdateFTPSrc.sh./erpHome/shell/setP.shecho`date`>$ERPHome/work/da/log/update/last.logexport DAHome=/home/ftpuser/pubif!test$(find$DAHome-type f|wc-l)-eq0thenecho`date`":Update source">>$UpdateLog2>&1echo"################Update the source################">> $UpdateLog2>&1echo$ERPHome>>$UpdateLog2>&1/usr/bin/cp-r$DAHome/*$ERPHome>>$UpdateLog2>&1#/usr/bin/cp-r$DAHome/*/erpHome/shell/src>>$UpdateLog2>&1#/usr/bin/rm-fre$DAHome/*>>$UpdateLog2>&1find$DAHome-type f-exec\rm-e{}\;>>$UpdateLog2>&1#echo"copy">>$UpdateLog2>&1#mail-s"$1update program"root<$UpdateLogecho`date`":Update source done">>$UpdateLog2>&1fiupdateSource.sh./erpHome/shell/setP.sh$ShellHome/updateSrc.sh bin$ShellHome/updateSrc.sh toc$ShellHome/updateFTPSrc.shupdateSrc.sh./erpHome/shell/setP.shecho`date`>$ERPHome/work/da/log/update/last.logexport DAHome=$ERPHome/work/da/$1if!test$(find$DAHome-type f|wc-l)-eq0thenecho`date`":Update source">>$UpdateLog2>&1echo"################Update the source################">> $UpdateLog2>&1echo$ERPHome>>$UpdateLog2>&1/usr/bin/cp-r$DAHome/*$ERPHome>>$UpdateLog2>&1#/usr/bin/cp-r$DAHome/*/erpHome/shell/src>>$UpdateLog2>&1#/usr/bin/rm-fre$DAHome/*>>$UpdateLog2>&1find$DAHome-type f-exec\rm-e{}\;>>$UpdateLog2>&1#echo"copy">>$UpdateLog2>&1#mail-s"$1update program"root<$UpdateLogecho`date`":Update source done">>$UpdateLog2>&1fiviewHtml.sh./erpHome/shell/setP.shmv$ERPHome/access.txt/erpHome/shell/logs/access_$YYMMDD.txtawk-F"\t"-f/erpHome/shell/filter.awk/erpHome/shell/logs/access_$YYMMDD.txt> /erpHome/shell/logs/temp.csvsort+3-n-r/erpHome/shell/logs/temp.csv>/erpHome/shell/logs/temp2.csvcat/erpHome/shell/htmlHead.txt>$ERPHome/public/$YYMMDD.htmlawk-F"\t"-f/erpHome/shell/formatHTML.awk/erpHome/shell/logs/temp2.csv>> $ERPHome/public/$YYMMDD.htmlcat/erpHome/shell/htmlFoot.txt>>$ERPHome/public/$YYMMDD.html。
Shell 脚本示例
Shell 脚本示例Sunday, December 18, 2016 3:58 PM1.简单示例2.一般结构∙shell类型∙函数∙主过程3.交互式脚本Shell下最简单的交互式命令:read脚本的参数代号(位置参数,数字多于一位用{}括起来):$0 脚本的文件名$1 第一个附加参数$2 第二个附加参数$3 ......$n4.Shell脚本语法4.1变量命名规则∙变量与变量之间以等号=来连接∙等号两边不能直接接空格符∙变量名称只能是英文字母与数字,但是数字不能做为开头字符∙若有空格符,可以使用双引号“或单引号‘来将变量内容结合起来注意:双引号内的特殊字符可以保有变量特性,但是单引号内的特殊字符则仅为一般字符∙必要时需要以字符\来将特殊字符(如:Enter , $ , \ , 空格符 , ‘等)变成一般字符∙若该变量需要在其他子程序中起作用,需要以export来使变量生效,如:export PATH ∙通常,大写字母的变量为系统的预设变量,自定义变量使用小写字母,以方便判断4.2变量声明和引用∙在shell中,所有没有声明的变量都默认是呈现字符串形式。
∙声明变量使用declare指令。
delcare [-afir] var=...-a 定义为数组array-f 定义为函数function-i 定义为整数integer-r 定义为只读readonly4.3变量的引用o格式:$变量名,或者${变量名}变量名为一个字符用方式一,变量名多于一个字符建议用第2中方式o例子:a=1abc="hello"echo $aecho ${abc}4.4数组BASH只支持一维数组,但参数个数没有限制。
数组赋值:(1) array=(var1 var2 var3 ... varN)(2) array=([0]=var1 [1]=var2 [2]=var3 ... [n]=varN)(3) array[0]=var1arrya[1]=var2...array[n]=varN计算数组元素个数:${#array[@]} 或者 ${#array[*]}BASH的特殊参数 @ 和 * 都表示“扩展位置参数”,形式稍有差异,但在数组里使用是可以通用的。
Shell脚本例子集合
Shell脚本例子集合本文由L3_wings贡献doc文档可能在WAP端浏览体验不佳。
建议您优先选择TXT,或下载源文件到本机查看。
# vi xx.sh 退出并保存 # chmod +x xx.sh # ./xx.sh -2.调试脚本的方法 # bash -x xx.sh 就可以调试了. -1.配置 secureCRT 的设置(我用的是 6.2.3 build313 版本,汉化版) 选项->会话选项(S)...->终端->仿真->终端(T)->把 VT100 改成 Xterm->点中 ANSI 颜色(A)和使用颜色方案(U)复选框. 这样就有颜色显示了. 选项->会话选项(S)...->终端->外观->字符编码(H)->从 Default 变到 UTF-8. 这样就有中文显示了.1.写一个脚本,执行后,打印一行提示";Please input a number:";,要求用户输入数值,然后打印出该数值,然后再次要求用户输入数值.直到用户输入";end";停止.# vi show_var.sh脚本内容:#!/bin/shunset varwhile [ "$var" != "end" ]do echo -n "please input a number: "read varif [ "$var" = "end" ]thenbreakfiecho "var is $var"done 命令保存后退出,并执行:# chmod +x show_var.sh #./show_var.shplease input a number: 1 var is 1 please input a number: s var is s please input a number: end #2.写一个脚本,测试位置参数# vi param.sh脚本内容:#!/bin/bash#test shellecho $0echo $1echo $2echo $?echo $*echo $#命令保存后退出,并执行: #chmod +x param.sh #./param.sh yema Bhanv edu network ./param.sh //程序名称 Yema //第一个参数 Bhanv //第二个参数 0 //程序执行结果 yema Bhanv edu network //传递参数所组成的字符串 4 //参数个数3.写一个脚本,可以根据参数文件名,以正确的参数调用tar 来解压缩 tar.gz 或 tar.bz2 文件.# vi tar_gz_bz2.sh脚本内容:#!/bin/shcase ${1##*.tar.} inbz2) tar jxvf $1;;gz) tar zxvf $1;;*) echo "wrong file type";;esac命令保存后退出,并执行:# chmod +x tar_gz_bz2.sh # ./tar_gz_bz2.sh # touch ";helloA"; > a.txt //写一个测试用的文件 # tar czvf a.tar.gz a.txt //把a.txt 压缩成 tar.gz 文件# rm -rf a.txt //删除 a.txt 来测试脚本# ls a.* a.tar.gz # ./tar_gz_bz2.sh a.tar.gz # ls a.* a.tar.gz a.txt //验证了正确性# touch ";helloB"; > b.txt //写一个测试用的文件 # tar cjvf b.tar.bz2 b.txt //把 b.txt 压缩成 tar.bz2 文件 # rm -rf b.txt //删除 b.txt 来测试脚本 # ls b.* b.tar.bz2 # ./tar_gz_bz2.sh b.tar.bz2 # ls b.* b.tar.bz2 b.txt //验证了正确性 # rm -rf a.txt a.tar.gz //删除测试用的文件 # rm -rf b.txt b.tar.bz2 //删除测试用的文件 4.小棍子显示# vi showstick.sh #!/bin/bash i=0 while [ $i -lt 10 ] do for j in '-' '\\' '|' '/' do echo -ne ";\033[1D$j"; usleep 50000 done ((i++)) done 保存 # chmod +x showstick.sh # ./showstick.sh 看效果.5.显示类似 wget 的进度# vi showwget.sh#!/bin/bashi=0while [ $i -lt 10 ]dofor j in '-' '\\' '|' '/'doecho -ne ";\033[1D$j";usleep 50000done((i++))done保存 #chmod +x showwget.sh # ./showwget.sh 看效果.6.定义 loop 的变量 1 2 3 4 5 是变量列表 #vi forlist.sh#!/bin/bash#for with listfor loop in 1 2 3 4 5doecho ${loop}done保存 # chmod +x forlist.sh # ./forlist.sh 看效果.7.读取文件中的每串字符,去掉了回车或者空格,输出每行就显示一个字符串. 编写文件 var.txt # vi var.txt 1 22保存# vi listfile.sh#!/bin/bashfor loop in `cat var.txt`doecho ${loop}done 保存 # chmod +x listfile.sh # ./listfile.sh 看效8.编写一个脚本自动生成一个 C 类 IP 地址段 IP 地址段网络部分由用户指定# vi ipaddr.sh#!/bin/bashfor ip in `seq 1 254`doecho ${1}.${ip}done 保存# chmod +x ipaddr.sh # ./ipaddr.sh 192.168.1 看效果.9.编写一个脚本自动生成一个 C 类 IP 地址段 IP 地址段网络部分由用户指定,主机结束部分由用户指定# vi ipaddr2.sh#!/bin/bashfor ip4 in `seq 1 ${2}`doecho ${1}.${ip4}done保存# chmod +x ipaddr2.sh # ./ipaddr2.sh 192.168.1 100 看效果.10.编写一个脚本自动生成一个 C 类 IP 地址段 IP 地址段网络部分由用户指定,主机结束部分由用户指定# vi ipaddr3.sh#!/bin/bashfor ip3 in `seq 1 5`dofor ip4 in `seq 1 ${2}`doecho ${1}.${ip3}.${ip4}donedone保存 # chmod +x ipaddr3.sh # ./ipaddr3.sh 192.168 2 100 看效果.11.编写一个脚本测试 while 的性能# vi menu-while.sh#!/bin/bashwhile [ ";1"; == ";1"; ]doclearecho "-------menu-----"echo "1) Show Time"echo "2) CPU load"echo "3) Memory free"echo "0) Exit"echo "---------------"echo -n "Enter you chose [0-3]:"read Chose case ${Chose} in0) exit ;;1) date +;;2) uptime | awk -F '[,]' '{print $1}';;3) free -m | awk '$1==";Mem:";{print $4}';;*) echo "This is not between 0-3.";;esacecho -n "Do you contine [y/n]:"readcontineif [ "${contine}" == "n" -o "${contine}" == "N" ]thenexitfidone保存 # chmod +x menu-while.sh # ./menu-while.sh 看效果.12.echo 颜色显示# vi showcolor.sh#!/bin/bashecho -e ";\033[40;35mHell,world! \033[0m";echo ";Hello,world";保存 # chmod +x showcolor.sh # ./showcolor.sh 看效果.13.sort 排序# vi showsort.sh#!/bin/bashsort -k3 -n -r -t: /etc/passwd保存 # chmod +x showsort.sh # ./showsort.sh 看效果.14.wc 统计字数# vi showwc.sh #!/bin/bash wc /etc/passwd保存 # chmod +x showwc.sh # ./showwc.sh 看效果.15.diff 判断文件的差异 # vi a.txt Hello World保存# vi b.txt Hello You保存 # vi showdiff.sh #!/bin/bash diff a.txt b.txt 保存 # chmod +x showdiff.sh # ./showdiff.sh15.diff 判断文件的差异# vi showawk.sh#!/bin/bashawk -F: '{print $1,$3}' /etc/passwd保存 # chmod +x showawk.sh # ./showawk.sh 看效果.16.test 判断文件的差异# vishowtest.sh#!/bin/bash#中间是 a 与操作,则都为 0 才得 0 #中间是 o 或操作,则有一真则真 0test -e /etc/passwd -a -e /etc/shadow echo $?test -e /etc/passwd -o -e /etc/groupsecho $?保存 # chmod +x showtest.sh # ./showtest.sh 看效果.17.输入判断# vi input.sh#!/bin/bash#input testecho -n "Enter your name:"read nameif [ "${name}" == "" ]thenecho "You did not enter any information"else echo "Your name:${name}"fi保存 # chmod +x input.sh # ./input.sh 看效果.18.文件拷贝# vi filecopy.sh#!/bin/bash#file copy# 2>/dev/null 丢掉错误提示if cp /etc/passwd passwd.bak >>2>/dev/nullthenecho "Good Copy!"elseecho "`basename $0`: error,could not copy"fi保存 # chmod +x filecopy.sh # ./filecopy.sh 看效果.19.case 选择效果# vi showcase.sh#!/bin/bash #case selectecho -n ";enter a number from 1 to 5:";read NUMcase $NUM in1) echo "you select 1";;2) echo "you select 2";;3) echo "you select 3";;4) echo "you select 4";;5) echo "you select 5";;*) echo "basename $This is not between 1 and 5";;esac保存 # chmod +x showcase.sh # ./showcase.sh 看效果.20.case 选择效果学生的考试成绩是 0-100 分,在 85 以上的要提示 you are the best!,在 70-84 显示 you get a good mark! ,在 60-74 的显示 come on!,60 分以下显示 You must study hard!# vi showpoint.sh#!/bin/bashecho -n "please input your mark:"read markcase $mark in100、90-99、85-89 100|9[0-9]|8[5-9]) echo "you are the best!";;80-84、70-79 8[0-4]|7[0-9]) echo "you get a good mark!";;70-74、60-69 7[0-4]|6[0-9]) echo "come on!";;00-59 [0-5][0-9]) echo "You must study hard!";;esac保存 # chmod +x showpoint.sh # ./showpoint.sh 看效果.21.用 echo 显示颜色# vi showcolors.sh#!/bin/bash T='gYw' # The test text echoecho ";default 40m 41m 42m 43m 44m 45m 46m 47m";## FGs 为前景(foreground), BG 为背景(background)for FGs in ' m' ' 1m' ' 30m' '1;30m' ' 31m' '1;31m' ' 32m' '1;32m' ' 33m' '1;33m' ' 34m' '1;34m' ' 35m' '1;35m' ' 36m' '1;36m' ' 37m' '1;37m'doFG=$(echo $FGs|tr -d ' ')echo -en "; $FGs \033[$FG $T "; for BG in 40m 41m 42m 43m 44m 45m 46m 47m; do echo -en "; \033[$FG\033[$BG $T \033[0m";doneechodoneecho保存 # chmod +x showcolors.sh # ./showcolors.sh 看效果.22.改变终端窗口的名称.这里使用了一个名为 help 的函数,该函数在脚本中使用了两次:# vi xtitlebar.sh#!/bin/bash # vim: set sw=4 ts=4 et:help() { cat << HELP xtitlebar -- change the name of an xterm, gnome-terminal or kde konsoleUSAGE: xtitlebar [-h] ";string_for_titelbar"; OPTIONS: -h help text EXAMPLE: xtitlebar ";cvs";HELP exit 0 }# in case of error or if -h is given we call the function help: [ -z ";$1"; ] && help [ ";$1"; = ";-h"; ] && help # send the escape sequence to change the xterm titelbar: echo -e ";\033[40;35m$1\033[0m";保存 # chmod +x xtitlebar.sh # ./xtitlebar.sh看效果.23.shift 用法# vi showshift.sh#!/bin/bashuntil [ $# -eq 0 ]doecho ";第一个参数为: $1 参数个数为: $#";shiftdone保存 # chmod +x showshift.sh # ./showshift.sh 1 2 3 4 第一个参数为: 1 参数个数为: 4 第一个参数为: 2 参数个数为: 3 第一个参数为: 3 参数个数为: 2 第一个参数为: 4 参数个数为: 1 看效果.shift 用法 2# vi showshift2.sh#!/bin/bashif [ $# -eq 0 ] thenecho ";Usage:x_shift2.sh 参数";exit 1 fisum=0until [ $# -eq 0 ]dosum=`expr $sum + $1`shiftdoneecho ";sum is: $sum";保存 # chmod +x showshift2.sh # ./showshift2.sh 10 20 15 sum is: 45 看效果.25.函数定义,调用 #vi showfunction.sh#!/bin/bashmessage(){echo "message"}let i=1while [ $i -le 3 ]domessagelet i=$i+1done保存 # chmod +x showfunction.sh # ./showfunction.sh26.函数定义,调用,参数传递,这里主要实现数的乘方计算.# vi showfunction2.sh#!/bin/bashpower(){x=$1y=$2count=1result=1while [ $count -le $y ]doresult=`expr $result \* $x`count=`expr $count + 1`donereturn $result}echo "Enter two numbers"read num1 num2power $num1 $num2answer=$?echo "$num1 to $num2 is $answer"保存 # chmod +x showfunction2.sh #./showfunction2.sh Enter two numbers 23 2 to 3 is 827.函数定义,调用,参数传递,这里主要实现数的乘方计算,使用递归调用.# vi showfunction3.sh#!/bin/bashpower(){x=$1y=$2if [ $y -eq 1 ]thenreturn $xelsey=`expr $y - 1`power $x $yresult=`expr $? \* $x`return $resultfi}echo "Enter two numbers"read num1 num2power $num1 $num2answer=$?echo "$num1 to $num2 is $answer"保存# chmod +x showfunction3.sh# ./showfunction3.sh Enter two numbers 32 3 to 2 is 9 看效果. 如果你输入 4 5 看看结果是什么 Enter two numbers 45 4 to 5 is 0 为什么是 0,不是 1024,我估计是计算溢出了.28.局部变量全局变量的测试. 默认情况下,所有函数的变量都是全局变量.你可以用 typeset 去声明一个局部变量# vi showfunction4.sh#!/bin/basheasy(){typeset aa=`expr 30 `b=`expr 30 `echo "easy a is " $aecho "easy b is " $b}a=10b=20easy $a $becho "global a is " $aecho "global b is " $b保存# chmod +x showfunction4.sh # ./showfunction4.sh easy a is 30 easy b is 30 global a is 10 global b is 30 看效果.29.如果要在脚本中多次使用函数,可以把它放在一个函数目录中,像一个普通文件一样,使用的时候把它放在脚本开始的地方模式: . functionfile ... 具体例子# vi power.sh#!/bin/bashpower(){x=$1y=$2if [ $y -eq 1 ]thenreturn $xelsey=`expr $y - 1`power $x $yresult=`expr $? \* $x`return $resultfi}保存# vi showfunction5.sh#!/bin/bash. power.shecho "Enter two numbers"read num1 num2power $num1 $num2answer=$?echo "$num1 to $num2 is $answer"保存# chmod +x power.sh # chmod +x showfunction5.sh # ./showfunction5.sh Enter two numbers 23 2 to 3 is 8 看效果.30. 函数使用# vi showfunction6.sh#!/bin/bash# file name ";showfunction6.sh";function nihao(){echo -n "nice to meet you ! "}function mingzi(){echo "小桥流水人家"}function out(){echo "即将退出..."echo "3 秒后退出!"sleep 1echo -n "."sleep 1echo -n "."sleep 1echo "."exit}nihao mingzi out保存# chmod +x showfunction6.sh # ./showfunction6.sh .31.实现对输入参数的分析,但是下面的使用case 表达式的例子无疑是一个不错的方法.# vi param.sh#!/bin/shhelp(){cat << HELP This is a generic command line parser demo. USAGE EXAMPLE: cmdparser -l hello -f -- -somefile1 somefile2 HELP exit 0 }while [ -n "$1" ]; docase $1 in-h) help;shift 1;; # function help is called-f) opt_f=1;shift 1;; # variable opt_f is set-l) opt_l=$2;shift 2;; # -l takes an argument -> shift by 2--) shift;break;; # end of options-*) echo ";error: no such option $1. -h for help";;exit 1;;*) break;;esacdoneecho ";opt_f is $opt_f";echo ";opt_l is $opt_l";echo ";first arg is $1";echo ";2nd arg is $2";你可以这样运行该脚本: # chmod +x param.sh # ./param.sh -l hello -f -- -somefile1 somefile2返回结果如下: opt_f is 1 opt_l is hello first arg is -somefile1 2nd arg is somefile2 这个脚本是如何工作的呢?脚本首先在所有输入命令行参数中进行循环,将输入参数与case 表达式进行比较,如果匹配则设置一个变量并且移除该参数.根据unix 系统的惯例,首先输入的应该是包含减号的参数.32. DONE OK PASSED FAILED WARNING 的 shell 颜色控制显示# vi colorbase.sh#!/bin/shBOOTUP=color # 第一设置BOOTUP 变量,默认就是color RES_COL=60# 第二设置设置在屏幕的第几列输出后面的";[ xxx ]"; ,默认是第60 列MOVE_TO_COL=";echo -en \\033[${RES_COL}G";# MOVE_TO_COL 是用于打印";OK"; 或者";FAILED"; ,或者";PASSED"; ,或者";WARNING"; 之前的部分,不含";["; SETCOLOR_SUCCESS=";echo -en \\033[1;32m";# SETCOLOR_SUCCESS 设置后面的字体都为绿色SETCOLOR_FAILURE=";echo -en \\033[1;31m";# SETCOLOR_FAILURE 设置后面将要输出的字体都为红色SETCOLOR_WARNING=";echo -en \\033[1;33m";# SETCOLOR_WARNING 设置后面将要输出的字体都为黄色SETCOLOR_NORMAL=";echo -en \\033[0;39m";# SETCOLOR_NORMAL 设置后面输出的字体都为白色(默认)echo_success(){# 下面是 echo_success 部分 [ ";$BOOTUP"; = ";color"; ] && $MOVE_TO_COL# 首先是打印 ";["; 之前的空格 echo -n ";[";# 然后打印 ";["; [ ";$BOOTUP"; = ";color"; ] && $SETCOLOR_SUCCESS# 设置字体为红色 echo -n $"; OK ";# 打印OK [ ";$BOOTUP"; = ";color"; ] && $SETCOLOR_NORMAL# 返回字体为白色 echo -n ";]";# 打印 ";]"; echo -ne ";\r";# 换行. return 0 # 返回 0,其他一律返回 1}echo_done(){# 下面是 echo_success 部分 [ ";$BOOTUP"; = ";color"; ] && $MOVE_TO_COL# 首先是打印 ";["; 之前的空格 echo -n ";[";# 然后打印";["; [ ";$BOOTUP"; = ";color"; ] && $SETCOLOR_SUCCESS# 设置字体为红色 echo -n $"; DONE ";# 打印DONE [ ";$BOOTUP"; = ";color"; ] && $SETCOLOR_NORMAL# 返回字体为白色 echo -n ";]";# 打印 ";]"; echo -ne ";\r";# 换行. return 0# 返回 0,其他一律返回 1}echo_failure(){[ ";$BOOTUP"; = ";color"; ] && $MOVE_TO_COLecho -n ";["; [ ";$BOOTUP"; = ";color"; ] && $SETCOLOR_FAILUREecho -n $"; FAILED "; [ ";$BOOTUP"; = ";color"; ] && $SETCOLOR_NORMALecho -n ";]";echo -ne ";\r"; return 1 }echo_passed() { [ ";$BOOTUP"; = ";color"; ] &&$MOVE_TO_COLecho -n ";["; [ ";$BOOTUP"; = ";color"; ] && $SETCOLOR_WARNINGecho -n $"; PASSED "; [ ";$BOOTUP"; = ";color"; ] && $SETCOLOR_NORMALecho -n ";]";echo -ne ";\r"; return 1 }echo_warning(){[ ";$BOOTUP"; = ";color"; ] && $MOVE_TO_COLecho -n ";["; [ ";$BOOTUP"; = ";color"; ] && $SETCOLOR_WARNINGecho -n $"; WARNING "; [ ";$BOOTUP"; = ";color"; ] && $SETCOLOR_NORMALecho -n ";]";echo -ne ";\r";return 1}保存 # vi testsuccess.sh #!/bin/sh . colorbase.sh echo_success echo ";I win."; echo_done echo ";I win."; echo_failure echo ";I think I will win."; echo_passed echo ";I passed."; echo_warning echo ";I think I will have no warning.";保存# chmod +x colorbase.sh # chmod +x testsuccess.sh # ./testsuccess.sh I win. [ OK ] I win. [ DONE ] I think I will win. [ FAILED ] I passed. [ PASSED ] I think I will have no warning. [ WARNING ] 看效果.33.如何计算一个日期是星期几# vi whichdate.sh #!/bin/bashgetdayofweek() { # Function dayofweek # Sample input:20020703 # Extract the month, day, and year year=`echo $1|cut -c1-4` month=`echo $1|cut -c5-6` day=`echo $1|cut -c7-8` b=`cal $month $year|wc -l ` cal $month $year |awk '{for(i=1;i<=NF;i++){if($i=='$day'){if (NR=='";$b";'-1){print i-1}else{print 7-NF+i-1}}}}' } getdayofweek $1 保存# chmod +x whichdate.sh # ./whichdate.sh 20100930 4 34. 自动让脚本调用其他脚本并输入相关的选择项,如果你没有安装expect 的话,请执行# yum install exepct 安装就可以了. # vi showfunction7.sh #!/bin/bash echo ";Enter one numbers"; read num1echo ";The number is $num1"; 保存# vi input.exp #!/usr/bin/expect -f spawn ./showfunction7.sh expect ";Enter one numbers";; send ";2\r";; interact;保存 # vi autoinput.sh #!/bin/bash ./input.exp# chmod +x showfunction7.sh # chmod +x input.exp # chmod +xautoinput.sh # ./autoinput.sh spawn ./showfunction7.sh Enter one numbers 2 The number is 2 看效果.35. 自动让脚本调用其他脚本并输入相关的选择项,多次调用输入 # vi showfunction8.sh #!/bin/bash echo ";Enter one numbers"; read num1 echo ";The number is $num1"; 保存 # vi input1.exp#!/usr/bin/expect -f spawn ./showfunction8.sh expect ";Enter one numbers";; send ";2\r";; interact; spawn ./showfunction8.sh expect ";Enter one numbers";; send ";3\r";; interact;保存 # vi autoinput1.sh #!/bin/bash ./input1.exp# chmod +x showfunction8.sh # chmod +x input1.exp # chmod +x autoinput1.sh # ./autoinput1.sh spawn ./showfunction8.sh Enter one numbers 2 The number is 2 spawn ./showfunction8.sh Enter one numbers 3 The number is 3 看效果.来源于网络,回归于网络. 我的邮箱:happy.every.day@/doc/9a2276731.html, QQ:48399956 快乐! 2010 年 9 月 30 日对我有用[0] 丢个板砖[0] 引用举报管理 TOP 精华推荐:借人气宣传一下自己开发的语言 Dao merryboy等级: #2 楼得分:0 回复于:2010-09-30 16:22:12 FAQ,参考信息: 1.位置参数 $1, $2, $3 等等... 位置参数,从命令行传递给脚本,或者是传递给函数.或者赋职给一个变量. 此数目可以任意多,但只有前9 个可以被访问,使用shift 命令可以改变这个限制. $0 $0 表示当前执行的进程名,script 本身的名字,或者在正则表达式中表示整行输出$# 命令行或者是位置参数的个数. $* 所有的位置参数,被作为一个单词. 注意:";$*";必须被";";引用. $@ 与$*同义,但是每个参数都是一个独立的";";引用字串,这就意味着参数被完整地传递, 并没有被解释和扩展.这也意味着,每个参数列表中的每个参数都被当成一个独立的单词. 注意:";$@";必须被";";引用.其他的特殊参数 $传递给脚本的 falg(使用 set 命令). 显示 shell 使用的当前选项,与 set 命令功能相同注意:这起初是 ksh 的特征,后来被引进到 Bash 中,但不幸的是,在 Bash 中它看上去也不能可靠的工作.使用它的一个可能的方法就是让这个脚本进行自我测试(查看是否是交互的). $! 在后台运行的最后的工作的 PID(进程 ID). $_ 保存之前执行的命令的最后一个参数. $? 命令,函数或者脚本本身的退出状态用于检查上一个命令,函数或者脚本执行是否正确.(在Linux 中,命令退出状态为0 表示该命令正确执行,任何非0 值表示命令出错.) $$ 脚本自身的进程ID.这个变量经常用来构造一个";unique";的临时文件名. 这通常比调用mktemp 来得简单. 注意事项:[1] 当前运行的脚本的 PID 为$$. [2] ";argument";和";parameter";这两个单词经常不加区分的使用.在这整本书中,这两个单词的意思完全相同.(在翻译的时候就未加区分,统统翻译成参数) 退出和返回退出状态(exit status) 函数返回一个被称为退出状态的值. 退出状态可以由 return 来指定 statement, 否则函数的退出状态是函数最后一个执行命令的退出状态(0 表示成功,非 0 表示出错代码). 退出状态 (exit status)可以在脚本中由$? 引用. 这个机制使脚本函数也可以像 C 函数一样有一个"; 返回值";. return 终止一个函数.return 命令[1]可选地带一个整数参数,这个整数作为函数的";返回值";返回给调用此函数的脚本,并且这个值也被赋给变量$?. while true 可以写为 while : 一、用户登陆进入系统后的系统环境变量$HOME 使用者自己的目录$PATH 执行命令时所搜寻的目录 $TZ 时区 $MAILCHECK 每隔多少秒检查是否有新的信件 $PS1 在命令列时的提示号 $PS2 当命令尚未打完时,Shell 要求再输入时的提示号 $MANPATH man 指令的搜寻路径二、特殊变量 $0 这个程序的执行名字 $n 这个程序的第 n 个参数值,n=1..9 $* 这个程序的所有参数 $# 这个程序的参数个数 $$ 这个程序的 PID $! 执行上一个指令的 PID $? 执行上一个指令的返回值三、shell 中的变元 * 任意字符串 ? 一个任意字符 [abc] a, b, c 三者中之一 [a-n] 从 a 到 n 的任一字符四、几个特殊字符表示 \b 退回 \c 打印一行时没有换行符这个我们经常会用到 \f 换页 \r 回车 \t 制表 \v 垂直制表\\ 反斜线本身五、判断文件的属性格式:-操作符 filename -e 文件存在返回 1, 否则返回 0 -r 文件可读返回 1,否则返回 0 -w 文件可写返回 1,否则返回 0 -x 文件可执行返回 1,否则返回 0 -o 文件属于用户本人返回 1, 否则返回 0 -z 文件长度为 0 返回 1, 否则返回 0. -f 文件为普通文件返回 1, 否则返回 0 -d 文件为目录文件时返回 1, 否则返回 0六、测试字符串字符串 1 = 字符串 2 当两个字串相等时为真字符串1 != 字符串2 当两个字串不等时为真 -n 字符串当字符串的长度大于0 时为真 -z 字符串当字符串的长度为 0 时为真字符串当串字符串为非空时为真七、测试两个整数关系数字 1 -eq 数字 2 两数相等为真数字 1 -ne 数字 2 两数不等为真数字 1 -gt 数字 2 数字 1 大于数字 2 为真数字 1 -ge 数字 2 数字 1 大于等于数字 2 为真数字 1 -lt 数字 2 数字 1 小于数字 2 为真数字 1 -le 数字 2 数字 1 小于等于数字 2 为真八、逻辑测试 -a 与 -o 或 ! 非 shell 中的特殊字符有 1、$ 美元符 2、\ 反斜杠 3、` 反引号 4、"; 双引号 5、,*,?,[,] 下面我一一举列说明一、$符号 1、echo $? 显示的是上一条指令退出状态 2、echo ";$?"; 效果同上3、echo '$?' 显示的是$? 4、echo \$? 显示的是$? 5、echo ";\$?"; 显示的是$? 大家可能已经看出 $符号在双引号中具有特殊意义双引号对$符号不起作用而单引号可以将特殊字符的的特殊意义屏蔽掉,使其能显示为字符本身,反斜杠也可以将特殊字符的特殊含义屏蔽掉,使特殊字符失去特殊含义.二、\ 反斜杠反斜杠的作用是将特殊符号字符的特殊含义屏蔽掉,使其还是原字符A=1234 echo \$A 显示为$A 如果不加\将显示为1234 echo \` 显示为` echo \"; 显示为双引号 echo \\ 显示为\ 三、` 反引号反引号的功能是命令替换,将反引号中的字符串做为命令来执行,我们在用 shell 编程时经常用的到将系统命令的执行结果赋给一个变量 A=`date` echo $A 显示的不是 date 而是当时的时间串比如有一文件 A 的内容如下 ABCDEFG 1234456 abcdefg B=`cat A|grep 234` # 检索文件 A 中含有字符串 234 的行 echo $B 将显示为 1234456 echo ";$B"; 将显示为什么? echo ";\$B"; 将显示为什么?读者自己试试四、";双引号在系统中有些特殊字符,为避免引用这些特殊字符往往用双引号或单引号将这些特殊字符引起来,使其不具有特殊含义. 但有一部分特殊字符在引号中还是具有特殊含义,用双引号引起来是不起作用的.本文中所列的前四个特殊字符在双引号中还是特殊字符.为了使其不具有特殊含义一是用单引号引进来二是用\反斜线使其失去作用. 比如我们想原样输出这些特殊字符echo ";";"; echo ";$"; echo ";\"; echo ";`"; 以上不是你所期望的结果,因为双引号对它们不起作用,你只能这样才能输出这些特殊字符的原形 echo '";' echo '$' echo '\' echo '`' 或 echo ";\";"; echo ";\$"; echo ";\\"; echo ";\`"; 将分别显示为 "; $ \ ` 五、其它特殊字符大家注意到,除了前四个特殊字符外,我将其它的特殊字符都放在一块,这是因为前四个特殊字符在双引号中还是具有特殊含义,所以单独拿出来讲,除此以外的特殊字符如果你要输出这些特殊字符的原形,你就可以用双引号或单引号引起来使其失去特殊含义. ,*,?,[,]对shell 有特殊含义但你可以用双引号引起来输入这些原形一、if 条件语句格式: if 条件表达式 then #当条件为真时执行以下语句命令列表 else #为假时执行以下语句命令列表 fi if 语句也可以嵌套使用 if 条件表达式 1 then if 条件表达式 2 then 命令列表 else if 条件表达式 3 then 命令列表 else 命令列表 fi fi else 命令列表 fi 你可以进行多层嵌套一个 if 语句一定要跟一个 fi 表示该层条件结束否则会造成语法错误结合前面讲的举例如下: 这里先讲一个条件语句中用到的命令test 表示测试 test 后面的条件是否为真 if test -f ";$1"; then lpr $1 else if test -d ";$1"; then cd $1 lpr $1 else echo ";$1 不是文件或目录"; fi fi以上的例子还可以改成如下所示 if test -f ";$1"; then lpr $1 elif test -d ";$1"; #elif 同 else if then (cd $1;lpr $1) else echo ";$1 不是文件或目录"; fi 以上的例子不知您是否看懂是什么意思吗?假如我们现在将这个例子保存为prfile chmod +x prfile 执行刚才的程序 ./prfile aaa 这个例子是检查你的输入的参数是否是一个文件如果是就打印如果是一个目录先转目录再打印如果即不是文件也不是目录给出提示二、多重条件测试语句 case 格式: case 字串 in 模式) 命令列表;; 模式) 命令列表;; .... esac 多重条件语句是以 case 开始以 esac 结束中间可以有多个条件列表功能是测试字串和和里面的模式有没有匹配的,有就执行里面的命令列表模式也可以是*号表示任意字串,每个模式里面的最后要心;;双引号结束,否则会发生语法错误. 现举例如下: case $1 in *.c) cc $1 ;; *.txt) lpr $1 ;; *) echo ";未知的类型"; esac 假如将以上内容保存在文件 abc 中 chmod +x abc 执行 ./abc a.c 将会对文件 a.c 进行编译执行 ./abc readme.txt 将会把文件通过打印机假如我将以上内容改一下,你是否会知道它的执行结果? case $1 in *) cc $1 ;; *.txt) lpr $1 ;; *.c) echo ";未知的类型"; esac 一. while 循环 while 命令格式 while 条件表 do 命令表 done 执行过程 Shell 首先执行条件表,如果条件表的最后一条语句的退出状态为零,则执行盾环体内的命令表,执行完后,再检查条件表, 如果退出状态为零将继续执行,如此循环往复直到条件表的最后一条语句的退出状态非零. 退出状态为零就是条件为真 True. 举例说明假如 shell 文件的内容如下: Sum=0 i=0 while true #true 是系统的关键词表示真 do i=`expr $i + 1` Sum=`expr $Sum + $i` if [ $i = ";100"; ] then break; fi done echo $i $Sum 最后这个程序显示的是 100 5050 这个程序的运算就是将 1 到 100 加起来下面将这个程序再改动一下 Sum=0 i=0 while [ $i != ";100"; ] doi=`expr $i + 1` Sum=`expr $Sum + $i` done echo $i $Sum 改动后的程序运算结果和上面是一样但程序比上面的要简练在这个循环中还可以以 until 做为测试条件它正好与 while 测试的条件相反,也就是当条件为假时将继续执行循环体内的语句,否则就退出循环体,下面还用这个例子. Sum=0 i=0 until [ $i = ";100"; ] do i=`expr $i + 1` Sum=`expr $Sum + $i` done echo $i $Sum 当 i 不等于 100 时循环就是当条件为假时循环,否则就退出,而第一个例子是当 i 不等于 100 时循环,也就是测试条件为真时循环. 二.for 循环命令格式: for 变量 in 名字列表 do 命令列表 done 这里的名字列表是一个由空格分隔的字符串列表,shell 在执行 for 循环时每次依次从名字表中取出一个字符串赋给循环变量作为变量的值. 在写 for 语句时,也可以省略 in 名字列表部分,这表示用当前的位置参数来代替这时的名字列表. 面举个例子,比如在你的电脑中有两个目录,一个是 aa,一个是 bb 在这两个目录中有 5 个相同的文件,但其中一个目录中的一个或多个文件刚刚修改过,现在我忘记刚才改的是那几个文件了,那么我靠已知的序码查找. 程序如下: for File in a1 a2 a3 a4 a5 do diff aa/$File bb/$File done 下面再举一个不带名字列表的例子 for File do echo $Filw done 文件内容保存在 a.sh 中并可执行我们在执行这个shell 程序时命令行如下: a.sh a1 a2 a3 a4 a5执行结果如下: a1 a2 a3 a4 a5 大家从这个例子中可以看到命令行的参数被逐一读入一次三.循环控制语句 break 命令不执行当前循环体内 break 下面的语句从当前循环退出. continue 命令是程序在本循体内忽略下面的语句,从循环头开始执行.。
实验4 SHELL脚本的编写(一)
广东技术师范学院实验报告学院:计科院专业:班级:成绩:姓名:学号:组别:组员:实验地点:实验日期:指导教师签名:实验4项目名称:SHELL脚本的编写(一)1、实验目的通过对典型的SHELL脚本进行验证,以及编写具有一定实用程度的SHELL 脚本,理解并掌握SHELL脚本的基本编写方法。
2、实验内容2.1什么是shell脚本要明白什么是shell脚本,首先要理解什么是脚本(script)。
脚本是指一种未经编译而直接解释执行的程序,最典型例子就是javascript程序。
我们知道,程序代码写好后,有两种方式让它执行。
一是通过编译器编译成二进制执行代码后提交给系统执行,而另一种则不经过编译,直接送给解释器解释执行。
shell脚本指的就是一种通过shell来解释并执行的程序。
UNIX中的shell,它既是一个界面程序,又是一个脚本的解释器,同时又能提供一种功能丰富的脚本语言供用户编写脚本程序。
用户只需要通过vi等编辑器将脚本编写好(脚本本身上还是一个文本),通过命令行的形式提交给shell,shell便会对其解释并执行了。
2.2 shell脚本与系统管理Shell脚本在系统管理上占有重要的位置。
原因在于系统管理的日常工作许多都是常规化的,例如日志管理、重要数据备份、账户管理、文件系统清理等工作,一次性地编写一个管理脚本程序,就能避免重复的管理工作。
当然,现在有许多管理工具供管理员使用,不是任何工作都需要编写一个shell脚本。
不过任何一个管理工具都不可能为特定某个应用业务度身定制,针对当前应用业务的需要编写shell脚本属于高级系统管理员应具备的能力。
此外,有一个问题值得讨论,利用其它高级语言也一样可以写管理程序,为什么要用shell脚本语言?这在于shell脚本最终提交给shell解释执行,因此可直接在程序中使用各种shell命令(c程序是不可能这样做的)。
这些shell命令从操作系统管理的角度来看,都涉及到系统资源申请、使用和释放,shell脚本只通过简单的命令即可实现,而高级语言却需要复杂的、大量的系统API函数调用。
shell脚本实例
shell脚本实例---学习的捷径就是练习写在前面:1.在linux里面是不在乎后缀名的,但是建议写上后缀名,如test.sh,这样一眼便看出这是shell程序。
2.如果不能运行,一般要执行chmod +x filename 使文件可执行3.执行格式一般为./test.sh,为了安全起见。
4.写shell脚本时最好要建立良好的习惯。
在每个 script 的档头处记录好∶(练习的时候免了吧)• script 的功能;•script 的版本资讯;•script 的作者与联络方式;•script 的版权宣告方式;•script 的 History (历史纪录);•script 内较特殊的指令,使用绝对路径的方式来下达;•script 运作时需要的环境变数预先宣告与设定。
来自: 鸟哥的私房菜注:鸟哥的shell用的是bash,不过建议写成 #!/bin/sh这样就可以使用系统默认版本的shell,而不一定就是用bash。
在获取命令的运行结果中,鸟哥用的是`(不是单引号'),建议用$(),更好一些。
# 请建立一支 script ,当你执行该 script 的时候,该 script 可以显示∶ 1. 你目前的身份(用 whoami ) 2. 你目前所在的目录 (用 pwd)view plaincopy to clipboardprint?1. #!/bin/bash2. echo -e "Your name is ==> $(whoami)"3. echo -e "The current directory is ==> `pwd`"1. #!/bin/bash2. read -p "Pleas input your birthday (MMDD, ex> 0709): " bir3. now=`date +%m%d`4. if [ "$bir" == "$now" ]; then5. echo "Happy Birthday to you!!!"6. elif [ "$bir" -gt "$now" ]; then7. year=`date +%Y`8. total_d=$(($((`date --date="$year$bir" +%s`-`date +%s`))/60/60/24))9. echo "Your birthday will be $total_d later"10. else11. year=$((`date +%Y`+1))12. total_d=$(($((`date --date="$year$bir" +%s`-`date +%s`))/60/60/24))13. echo "Your birthday will be $total_d later"14. fi# 让使用者输入一个数字,程式可以由 1+2+3... 一直累加到使用者输入的数字为止。
8个实用的Shell脚本分享-电脑资料
8个实用的Shell脚本分享-电脑资料这篇文章主要介绍了8个实用的Shell脚本分享,本文给出了判断输入为数字、字符或其他、求平均数、自减输出、在文件中添加前缀、批量测试文件是否存在等实用脚本,需要的朋友可以参考下几个Shell脚本的例子,觉得还不错,。
【例子:001】判断输入为数字,字符或其他代码如下:#!/bin/bashread -p "Enter a number or string here:" inputcase $input in[0-9]) echo -e "Good job, Your input is a numberic! \" ;;[a-zA-Z]) echo -e "Good job, Your input is a character! \" ;;*) echo -e "Your input is wrong, input again! \" ;;esac【例子:002】求平均数代码如下:#!/bin/bash# Calculate the average of a series of numbers.SCORE="0"AVERAGE="0"SUM="0"NUM="0"while true; doecho -n "Enter your score [0-100%] (‘q‘ for quit): "; read SCORE;if (("$SCORE" < "0")) || (("$SCORE" > "100")); thenecho "Be serious. Common, try again: "elif [ "$SCORE" == "q" ]; thenecho "Average rating: $AVERAGE%."elseSUM=$[$SUM + $SCORE] NUM=$[$NUM + 1] AVERAGE=$[$SUM / $NUM] fidoneecho "Exiting."【例子:003】自减输出代码如下: [scriptname: doit.sh]while (( $# > 0 ))doecho $*shiftdone/> ./doit.sh a b c d ea b c d eb c d ec d ed ee【例子:004】在文件中添加前缀代码如下:# 人名列表# cat namelistJameBobTomJerryAliceJohn# 脚本程序# cat namelist.sh#!/bin/bashfor name in $(cat namelist)doecho "name= " $namedoneecho "The name is out of namelist file" # 输出结果# ./namelist.shname= Jamename= Bobname= Tomname= Jerryname= Sherryname= Alicename= John【例子:005】批量测试文件是否存在代码如下:[root@host ~]# cat testfile.sh#!/bin/bashfor file in test*.shdoif [ -f $file ];thenecho "$file existed."fidone[root@host ~]# ./testfile.shtest.sh existed.test1.sh existed.test2.sh existed.test3.sh existed.test4.sh existed.test5.sh existed.test78.sh existed.test_dev_null.sh existed.testfile.sh existed.【例子:005】用指定大小文件填充硬盘代码如下:[root@host ~]# df -ih /tmpFilesystem Inodes IUsed IFree IUse% Mounted on /dev/mapper/vg00-lvol51000K 3.8K 997K 1% /tmp[root@host ~]# cat cover_disk.sh#!/bin/env bashcounter=0max=3800remainder=0while truedo((counter=counter+1))if [ ${#counter} -gt $max ];thenbreakfi((remainder=counter%1000))if [ $remainder -eq 0 ];thenecho -e "counter=$counter\date=" $(date)mkdir -p /tmp/tempcat < testfile > "/tmp/temp/myfile.$counter"if [ $? -ne 0 ];thenecho "Failed to write file to Disk."exit 1fidoneecho "Done!"[root@host ~]# ./cover_disk.shcounter=1000 date= Wed Sep 10 09:20:39 HKT 2014 counter=2000 date= Wed Sep 10 09:20:48 HKT 2014 counter=3000 date= Wed Sep 10 09:20:56 HKT 2014 cat: write error: No space left on deviceFailed to write file to Disk.dd if=/dev/zero f=testfile bs=1M count=1【例子:006】通过遍历的方法读取配置文件代码如下:[root@host ~]# cat hosts.allow127.0.0.1127.0.0.2127.0.0.3127.0.0.4127.0.0.5127.0.0.6127.0.0.7127.0.0.8127.0.0.9[root@host ~]# cat readlines.sh#!/bin/env bashwhile read LINE;dohosts_allow[$i]=$LINE((i++))done < hosts.allowfor ((i=1;i<=${#hosts_allow[@]};i++)); do echo ${hosts_allow[$i]}doneecho "Done"[root@host ~]# ./readlines.sh127.0.0.2127.0.0.3127.0.0.4127.0.0.5127.0.0.6127.0.0.7127.0.0.8127.0.0.9Done【例子:007】简单正则表达式应用代码如下:[root@host ~]# cat regex.sh#!/bin/env sh#Filename: regex.shregex="[A-Za-z0-9]{6}"if [[ $1 =~ $regex ]]thennum=$1echo $numelseecho "Invalid entry"exit 1fi[root@host ~]# ./regex.sh 123abc123abc#!/bin/env bash#Filename: validint.shvalidint(){ret=`echo $1 | awk ‘{start = match($1,/^-?[0-9]+$/);if (start == 0) print "1";else print "0"}‘`return $ret}validint $1if [ $? -ne 0 ]; thenecho "Wrong Entry"exit 1elseecho "OK! Input number is:" $1fi【例子:008】简单的按日期备份文件代码如下:#!/bin/bashNOW=$(date +"%m-%d-%Y") # 当前日期FILE="backup.$NOW.tar.gz" # 备份文件echo "Backing up data to /tmp/backup.$NOW.tar.gz file, please wait..." #打印信息tar xcvf /tmp/backup.$NOW.tar.gz /home/ /etc/ /var # 同时备份多个文件到指定的tar压缩文件中echo "Done..."。
shell编程实例
shell编程实例Shell编程是一种适用于Unix和Linux操作系统的脚本语言,通过编写一系列的Shell脚本,可以实现自动化任务、文件处理、系统管理等多种功能。
本文将通过几个实际的Shell编程实例,向读者展示如何使用Shell脚本来完成一些常见的任务。
实例一:文件备份假设我们需要定期备份一个指定目录下的文件到另一个目录中。
首先,我们可以使用以下Shell脚本来实现文件备份的任务:```shell#!/bin/bash# 指定源目录和目标目录source_dir="/path/to/source"target_dir="/path/to/target"# 根据日期生成备份文件名backup_filename="backup_$(date +%Y%m%d).tar.gz"# 创建目标目录(如果不存在)mkdir -p "$target_dir"# 执行文件备份tar -zcf "$target_dir/$backup_filename" "$source_dir"```该脚本首先指定了源目录和目标目录的路径,然后使用`$(date +%Y%m%d)`来生成当前日期的备份文件名。
接着,使用`mkdir -p`命令创建目标目录(如果不存在),最后使用`tar`命令打包源目录并将备份文件保存到目标目录中。
实例二:文件搜索和替换假设我们需要在一个文件夹下的所有文件中,查找并替换特定的字符串。
我们可以使用以下Shell脚本来实现文件搜索和替换的任务:```shell#!/bin/bash# 指定文件夹路径和要查找的字符串及替换字符串folder="/path/to/folder"search_string="old_string"replace_string="new_string"# 搜索并替换文件内容grep -rl "$search_string" "$folder" | xargs sed -i"s/$search_string/$replace_string/g"```该脚本首先指定了文件夹路径、要查找的字符串以及替换字符串。
LinuxShellBash精彩脚本示例
Linux Shell Bash 精彩脚本示例原文地址:/content/10/0303/18/155970_17453384.shtml这些脚本展示了一些有趣的shell编程技术, 但是它们并不适合放入本文档的文本讲解中.不过它们还是非常有用, 运行和分析它们都是很有意思的事.译者: 这里留给那些有能力而且有多余时间的读者来详读, 个人认为翻译这些注释有点画蛇添足.例子A-1. mailformat: 格式化一个e-mail消息1 #!/bin/bash2 # mail-format.sh (ver. 1.1): Format e-mail messages.34 # Gets rid of carets, tabs, and also folds excessively long lines.56 # =================================================================7 # Standard Check for Script Argument(s)8 ARGS=19 E_BADARGS=6510 E_NOFILE=661112 if [ $# -ne $ARGS ] # Correct number of arguments passed to script?13 then14 echo "Usage: `basename $0` filename"15 exit $E_BADARGS16 fi1718 if [ -f "$1" ] # Check if file exists.19 then20 file_name=$121 else22 echo "File \"$1\" does not exist."23 exit $E_NOFILE24 fi25 # =================================================================2627 MAXWIDTH=70 # Width to fold excessively long lines to.2829 # ---------------------------------30 # A variable can hold a sed script.31 sedscript='s/^>//32 s/^ *>//33 s/^ *//34 s/ *//'35 # ---------------------------------3637 # Delete carets and tabs at beginning of lines,38 #+ then fold lines to $MAXWIDTH characters.39 sed "$sedscript" $1 | fold -s --width=$MAXWIDTH40 # -s option to "fold"41 #+ breaks lines at whitespace, if possible.424344 # This script was inspired by an article in a well-known trade journal45 #+ extolling a 164K MS Windows utility with similar functionality.46 #47 # An nice set of text processing utilities and an efficient48 #+ scripting language provide an alternative to bloated executables.例子A-2. rn: 一个非常简单的文件重命名工具这个脚本是例子12-19的一个修改版.1 #! /bin/bash2 #3 # Very simpleminded filename "rename" utility (based on "lowercase.sh").4 #5 # The "ren" utility, by Vladimir Lanin (**************.edu),6 #+ does a much better job of this.789 ARGS=210 E_BADARGS=6511 ONE=1 # For getting singular/plural right (see below).1213 if [ $# -ne "$ARGS" ]14 then15 echo "Usage: `basename $0` old-pattern new-pattern"16 # As in "rn gif jpg", which renames all gif files in working directory to jpg.17 exit $E_BADARGS18 fi1920 number=0 # Keeps track of how many files actually renamed.212223 for filename in *$1* #Traverse all matching files in directory.24 do25 if [ -f "$filename" ] # If finds match...26 then27 fname=`basename $filename` # Strip off path.28 n=`echo $fname | sed -e "s/$1/$2/"` # Substitute new for old in filename.29 mv $fname $n # Rename.30 let "number += 1"31 fi32 done3334 if [ "$number" -eq "$ONE" ] # For correct grammar.35 then36 echo "$number file renamed."37 else38 echo "$number files renamed."39 fi4041 exit 0424344 # Exercises:45 # ---------46 # What type of files will this not work on?47 # How can this be fixed?48 #49 # Rewrite this script to process all the files in a directory50 #+ containing spaces in their names, and to rename them,51 #+ substituting an underscore for each space.例子A-3. blank-rename: 重命名包含空白的文件名这是上一个脚本的简化版.10 for filename in * #Traverse all files in directory.11 do12 echo "$filename" | grep -q " " # Check whether filename13 if [ $? -eq $FOUND ] #+ contains space(s).14 then15 fname=$filename # Strip off path.16 n=`echo $fname | sed -e "s/ /_/g"` # Substitute underscore for blank.17 mv "$fname" "$n" # Do the actual renaming.18 let "number += 1"19 fi20 done2122 if [ "$number" -eq "$ONE" ] # For correct grammar.23 then24 echo "$number file renamed."25 else26 echo "$number files renamed."27 fi2829 exit 0例子A-4. encryptedpw: 使用一个本地加密口令, 上传到一个ftp服务器.45 # Note that this is still rather insecure,6 #+ since the decrypted password is sent in the clear.7 # Use something like "ssh" if this is a concern.89 E_BADARGS=651011 if [ -z "$1" ]12 then13 echo "Usage: `basename $0` filename"14 exit $E_BADARGS15 fi1617 Username=bozo # Change to suit.18 pword=/home/bozo/secret/password_encrypted.file19 # File containing encrypted password.2021 Filename=`basename $1` # Strips pathname out of file name.2223 Server="XXX"24 Directory="YYY" # Change above to actual server name & directory.252627 Password=`cruft <$pword` # Decrypt password.28 # Uses the author's own "cruft" file encryption package,29 #+ based on the classic "onetime pad" algorithm,30 #+ and obtainable from:31 #+ Primary-site: ftp:///pub/Linux/utils/file32 #+ cruft-0.2.tar.gz [16k]333435 ftp -n $Server <<End-Of-Session36 user $Username $Password37 binary38 bell39 cd $Directory40 put $Filename41 bye42 End-Of-Session43 # -n option to "ftp" disables auto-logon.44 # Note that "bell" rings 'bell' after each file transfer.4546 exit 0例子A-5. copy-cd: 拷贝一个数据CD1 #!/bin/bash2 # copy-cd.sh: copying a data CD34 CDROM=/dev/cdrom # CD ROM device5 OF=/home/bozo/projects/cdimage.iso # output file6 # /xxxx/xxxxxxx/ Change to suit your system.7 BLOCKSIZE=20488 SPEED=2 # May use higher speed if supported.9 DEVICE=cdrom10 # DEVICE="0,0" on older versions of cdrecord.1112 echo; echo "Insert source CD, but do *not* mount it."13 echo "Press ENTER when ready. "14 read ready # Wait for input, $ready not used.1516 echo; echo "Copying the source CD to $OF."17 echo "This may take a while. Please be patient."1819 dd if=$CDROM of=$OF bs=$BLOCKSIZE # Raw device copy.202122 echo; echo "Remove data CD."23 echo "Insert blank CDR."24 echo "Press ENTER when ready. "25 read ready # Wait for input, $ready not used.2627 echo "Copying $OF to CDR."2829 cdrecord -v -isosize speed=$SPEED dev=$DEVICE $OF30 # Uses Joerg Schilling's "cdrecord" package (see its docs).31 # http://www.fokus.gmd.de/nthp/employees/schilling/cdrecord.html323334 echo; echo "Done copying $OF to CDR on device $CDROM."3536 echo "Do you want to erase the image file (y/n)? " # Probably a huge file.37 read answer3839 case "$answer" in40 [yY]) rm -f $OF41 echo "$OF erased."42 ;;43 *) echo "$OF not erased.";;44 esac4546 echo4748 # Exercise:49 # Change the above "case" statement to also accept "yes" and "Yes" as input.5051 exit 0例子A-6. Collatz序列12 # 7) Loop back to step 3 (for specified number of iterations).13 #14 # The theory is that every sequence,15 #+ no matter how large the initial value,16 #+ eventually settles down to repeating "4,2,1..." cycles,17 #+ even after fluctuating through a wide range of values.18 #19 # This is an instance of an "iterate",20 #+ an operation that feeds its output back into the input.21 # Sometimes the result is a "chaotic" series.222324 MAX_ITERATIONS=20025 # For large seed numbers (>32000), increase MAX_ITERATIONS.2627 h=${1:-$$} # Seed28 # Use $PID as seed,29 #+ if not specified as command-line arg.3031 echo32 echo "C($h) --- $MAX_ITERATIONS Iterations"33 echo3435 for ((i=1; i<=MAX_ITERATIONS; i++))36 do3738 echo -n "$h "39 # ^^^^^40 # tab4142 let "remainder = h % 2"43 if [ "$remainder" -eq 0 ] # Even?44 then45 let "h /= 2" # Divide by 2.46 else47 let "h = h*3 + 1" # Multiply by 3 and add 1.48 fi495051 COLUMNS=10 # Output 10 values per line.52 let "line_break = i % $COLUMNS"53 if [ "$line_break" -eq 0 ]54 then例子A-7. days-between: 计算两个日期之间天数差1 #!/bin/bash2 # days-between.sh: Number of days between two dates.3 # Usage: ./days-between.sh [M]M/[D]D/YYYY [M]M/[D]D/YYYY4 #5 # Note: Script modified to account for changes in Bash 2.05b6 #+ that closed the loophole permitting large negative7 #+ integer return values.89 ARGS=2 # Two command line parameters expected.10 E_PARAM_ERR=65 # Param error.1112 REFYR=1600 # Reference year.13 CENTURY=10014 DIY=36515 ADJ_DIY=367 # Adjusted for leap year + fraction.16 MIY=1217 DIM=3118 LEAPCYCLE=41920 MAXRETVAL=255 # Largest permissable21 #+ positive return value from a function.2223 diff= # Declare global variable for date difference.24 value= # Declare global variable for absolute value.25 day= # Declare globals for day, month, year.26 month=27 year=282930 Param_Error () # Command line parameters wrong.31 {32 echo "Usage: `basename $0` [M]M/[D]D/YYYY [M]M/[D]D/YYYY"33 echo " (date must be after 1/3/1600)"34 exit $E_PARAM_ERR35 }363738 Parse_Date () # Parse date from command line params.39 {40 month=${1%%/**}41 dm=${1%/**} # Day and month.42 day=${dm#*/}43 let "year = `basename $1`" # Not a filename, but works just the same.44 }454647 check_date () # Checks for invalid date(s) passed.48 {49 [ "$day" -gt "$DIM" ] || [ "$month" -gt "$MIY" ] || [ "$year" -lt "$REFYR" ] && Param_Error50 # Exit script on bad value(s).51 # Uses "or-list / and-list".52 #53 # Exercise: Implement more rigorous date checking.54 }555657 strip_leading_zero () # Better to strip possible leading zero(s)58 { #+ from day and/or month59 return ${1#0} #+ since otherwise Bash will interpret them60 } #+ as octal values (POSIX.2, sect 2.9.2.1).616263 day_index () # Gauss' Formula:64 { # Days from Jan. 3, 1600 to date passed as param.6566 day=$167 month=$268 year=$36970 let "month = $month - 2"71 if [ "$month" -le 0 ]72 then73 let "month += 12"74 let "year -= 1"75 fi7677 let "year -= $REFYR"78 let "indexyr = $year / $CENTURY"798081 let "Days = $DIY*$year + $year/$LEAPCYCLE - $indexyr + $indexyr/$LEAPCYCLE + $ADJ_DIY*$month/$MIY + $day - $DIM"82 # For an in-depth explanation of this algorithm, see83 #+ http://home.t-online.de/home/berndt.schwerdtfeger/cal.htm848586 echo $Days8788 }899091 calculate_difference () # Difference between to day indices.92 {93 let "diff = $1 - $2" # Global variable.94 }959697 abs () # Absolute value98 { # Uses global "value" variable.99 if [ "$1" -lt 0 ] # If negative100 then #+ then101 let "value = 0 - $1" #+ change sign,102 else #+ else103 let "value = $1" #+ leave it alone.104 fi105 }106107108109 if [ $# -ne "$ARGS" ] # Require two command line params. 110 then111 Param_Error112 fi113114 Parse_Date $1115 check_date $day $month $year # See if valid date.116117 strip_leading_zero $day # Remove any leading zeroes 118 day=$? #+ on day and/or month.119 strip_leading_zero $month120 month=$?121122 let "date1 = `day_index $day $month $year`"123124125 Parse_Date $2126 check_date $day $month $year127128 strip_leading_zero $day129 day=$?130 strip_leading_zero $month131 month=$?132133 date2=$(day_index $day $month $year) # Command substitution.134135136 calculate_difference $date1 $date2137138 abs $diff # Make sure it's positive. 139 diff=$value140141 echo $diff142143 exit 0144 # Compare this script with145 #+ the implementation of Gauss' Formula in a C program at:146 #+ /software/datedif例子A-8. 构造一个"字典"1 #!/bin/bash2 # makedict.sh [make dictionary]34 # Modification of /usr/sbin/mkdict script.5 # Original script copyright 1993, by Alec Muffett.6 #7 # This modified script included in this document in a manner8 #+ consistent with the "LICENSE" document of the "Crack" package9 #+ that the original script is a part of.1011 # This script processes text files to produce a sorted list12 #+ of words found in the files.13 # This may be useful for compiling dictionaries14 #+ and for lexicographic research.151617 E_BADARGS=651819 if [ ! -r "$1" ] # Need at least one20 then #+ valid file argument.21 echo "Usage: $0 files-to-process"22 exit $E_BADARGS23 fi242526 # SORT="sort" # No longer necessary to define options27 #+ to sort. Changed from original script.2829 cat $* | # Contents of specified files to stdout.30 tr A-Z a-z | # Convert to lowercase.31 tr ' ' '\012' | # New: change spaces to newlines.32 # tr -cd '\012[a-z][0-9]' | # Get rid of everythingnon-alphanumeric33 #+ (original script).34 tr -c '\012a-z' '\012' | # Rather than deleting35 #+ now change non-alpha to newlines.36 sort | # $SORT options unnecessary now.37 uniq | # Remove duplicates.例子A-9. Soundex转换1 #!/bin/bash2 # soundex.sh: Calculate "soundex" code for names34 # =======================================================5 # Soundex script6 # by7 # Mendel Cooper8 # ***********************9 # 23 January, 200210 #11 # Placed in the Public Domain.12 #13 # A slightly different version of this script appeared in14 #+ Ed Schaefer's July, 2002 "Shell Corner" column15 #+ in "Unix Review" on-line,16 #+ /documents/uni1026336632258/17 # =======================================================181920 ARGCOUNT=1 # Need name as argument.21 E_WRONGARGS=702223 if [ $# -ne "$ARGCOUNT" ]24 then25 echo "Usage: `basename $0` name"26 exit $E_WRONGARGS27 fi282930 assign_value () # Assigns numerical value31 { #+ to letters of name.3233 val1=bfpv # 'b,f,p,v' = 134 val2=cgjkqsxz # 'c,g,j,k,q,s,x,z' = 235 val3=dt # etc.36 val4=l37 val5=mn38 val6=r3940 # Exceptionally clever use of 'tr' follows.41 # Try to figure out what is going on here.4243 value=$( echo "$1" \44 | tr -d wh \45 | tr $val1 1 | tr $val2 2 | tr $val3 3 \46 | tr $val4 4 | tr $val5 5 | tr $val6 6 \47 | tr -s 123456 \48 | tr -d aeiouy )4950 # Assign letter values.51 # Remove duplicate numbers, except when separated by vowels.52 # Ignore vowels, except as separators, so delete them last.53 # Ignore 'w' and 'h', even as separators, so delete them first.54 #55 # The above command substitution lays more pipe than a plumber <g>.5657 }585960 input_name="$1"61 echo62 echo "Name = $input_name"636465 # Change all characters of name input to lowercase.66 # ------------------------------------------------67 name=$( echo $input_name | tr A-Z a-z )68 # ------------------------------------------------69 # Just in case argument to script is mixed case.707172 # Prefix of soundex code: first letter of name.73 # --------------------------------------------747576 char_pos=0 # Initialize character position.77 prefix0=${name:$char_pos:1}78 prefix=`echo $prefix0 | tr a-z A-Z`79 # Uppercase 1st letter of soundex.8081 let "char_pos += 1" # Bump character position to 2nd letter of name.82 name1=${name:$char_pos}838485 # ++++++++++++++++++++++++++ Exception Patch+++++++++++++++++++++++++++++++++86 # Now, we run both the input name and the name shifted one char to the right87 #+ through the value-assigning function.88 # If we get the same value out, that means that the first two characters89 #+ of the name have the same value assigned, and that one should cancel.90 # However, we also need to test whether the first letter of the name91 #+ is a vowel or 'w' or 'h', because otherwise this would bollix things up.9293 char1=`echo $prefix | tr A-Z a-z` # First letter of name, lowercased.9495 assign_value $name96 s1=$value97 assign_value $name198 s2=$value99 assign_value $char1100 s3=$value101 s3=9$s3 # If first letter of name is a vowel102 #+ or 'w' or 'h',103 #+ then its "value" will be null (unset).104 #+ Therefore, set it to 9, an otherwise105 #+ unused value, which can be tested for.106107108 if [[ "$s1" -ne "$s2" || "$s3" -eq 9 ]]109 then110 suffix=$s2111 else112 suffix=${s2:$char_pos}113 fi114 # ++++++++++++++++++++++ end Exception Patch+++++++++++++++++++++++++++++++++115116117 padding=000 # Use at most 3 zeroes to pad.118119120 soun=$prefix$suffix$padding # Pad with zeroes.121122 MAXLEN=4 # Truncate to maximum of 4 chars. 123 soundex=${soun:0:$MAXLEN}124125 echo "Soundex = $soundex"126127 echo128129 # The soundex code is a method of indexing and classifying names 130 #+ by grouping together the ones that sound alike.131 # The soundex code for a given name is the first letter of the name, 132 #+ followed by a calculated three-number code.133 # Similar sounding names should have almost the same soundex codes. 134135 # Examples:136 # Smith and Smythe both have a "S-530" soundex.137 # Harrison = H-625138 # Hargison = H-622139 # Harriman = H-655140141 # This works out fairly well in practice, but there are numerous anomalies.142 #143 #144 # The U.S. Census and certain other governmental agencies use soundex,145 # as do genealogical researchers.146 #147 # For more information,148 #+ see the "National Archives and Records Administration home page", 149 #+ /genealogy/soundex/soundex.html150151例子A-10. "Game of Life"1 #!/bin/bash2 # life.sh: "Life in the Slow Lane"3 # Version 2: Patched by Daniel Albers4 #+ to allow non-square grids as input.56 ###################################################################### #7 # This is the Bash script version of John Conway's "Game of Life". #8 # "Life" is a simple implementation of cellular automata. #9 #--------------------------------------------------------------------- #10 # On a rectangular grid, let each "cell" be either "living" or "dead". #11 # Designate a living cell with a dot, and a dead one with a blank space.#12 # Begin with an arbitrarily drawn dot-and-blank grid, #13 #+ and let this be the starting generation, "generation 0". #14 # Determine each successive generation by the following rules: #15 # 1) Each cell has 8 neighbors, the adjoining cells #16 #+ left, right, top, bottom, and the 4 diagonals. #17 # 123 #18 # 4*5#19 # 678 #20 # #21 # 2) A living cell with either 2 or 3 living neighbors remains alive. #22 # 3) A dead cell with 3 living neighbors becomes alive (a "birth"). #23 SURVIVE=2 #24 BIRTH=3 #25 # 4) All other cases result in a dead cell for the next generation. #26 ###################################################################### #272829 startfile=gen0 # Read the starting generation from the file "gen0".30 # Default, if no other file specified when invoking script.31 #32 if [ -n "$1" ] # Specify another "generation 0" file.33 then34 startfile="$1"35 fi3637 ############################################38 # Abort script if "startfile" not specified39 #+ AND40 #+ "gen0" not present.4142 E_NOSTARTFILE=684344 if [ ! -e "$startfile" ]45 then46 echo "Startfile \""$startfile"\" missing!"47 exit $E_NOSTARTFILE48 fi49 ############################################505152 ALIVE1=.53 DEAD1=_54 # Represent living and "dead" cells in the start-up file.5556 # ---------------------------------------------------------- #57 # This script uses a 10 x 10 grid (may be increased,58 #+ but a large grid will will cause very slow execution).59 ROWS=1060 COLS=1061 # Change above two variables to match grid size, if necessary.62 # ---------------------------------------------------------- #6364 GENERATIONS=10 # How many generations to cycle through.65 # Adjust this upwards,66 #+ if you have time on your hands.6768 NONE_ALIVE=80 # Exit status on premature bailout,69 #+ if no cells left alive.70 TRUE=071 FALSE=172 ALIVE=073 DEAD=17475 avar= # Global; holds current generation.76 generation=0 # Initialize generation count.7778 #=================================================================798081 let "cells = $ROWS * $COLS"82 # How many cells.8384 declare -a initial # Arrays containing "cells".85 declare -a current8687 display ()88 {8990 alive=0 # How many cells "alive" at any given time.91 # Initially zero.9293 declare -a arr94 arr=( `echo "$1"` ) # Convert passed arg to array.9596 element_count=${#arr[*]}9798 local i99 local rowcheck100101 for ((i=0; i<$element_count; i++))102 do103104 # Insert newline at end of each row.105 let "rowcheck = $i % COLS"106 if [ "$rowcheck" -eq 0 ]107 then108 echo # Newline.109 echo -n " " # Indent.110 fi111112 cell=${arr}113114 if [ "$cell" = . ]115 then116 let "alive += 1"117 fi118119 echo -n "$cell" | sed -e 's/_/ /g'120 # Print out array and change underscores to spaces.121 done122123 return124125 }126127 IsValid () # Test whether cell coordinate valid.128 {129130 if [ -z "$1" -o -z "$2" ] # Mandatory arguments missing? 131 then132 return $FALSE133 fi134135 local row136 local lower_limit=0 # Disallow negativecoordinate.137 local upper_limit138 local left139 local right140141 let "upper_limit = $ROWS * $COLS - 1" # Total number of cells. 142143144 if [ "$1" -lt "$lower_limit" -o "$1" -gt "$upper_limit" ]145 then146 return $FALSE # Out of array bounds.147 fi148149 row=$2150 let "left = $row * $COLS" # Left limit.151 let "right = $left + $COLS - 1" # Right limit.152153 if [ "$1" -lt "$left" -o "$1" -gt "$right" ]154 then155 return $FALSE # Beyond row boundary.156 fi157158 return $TRUE # Valid coordinate.159160 }161162163 IsAlive () # Test whether cell is alive.164 # Takes array, cell number, state of cell as arguments.165 {166 GetCount "$1" $2 # Get alive cell count in neighborhood. 167 local nhbd=$?168169170 if [ "$nhbd" -eq "$BIRTH" ] # Alive in any case.171 then172 return $ALIVE173 fi174175 if [ "$3" = "." -a "$nhbd" -eq "$SURVIVE" ]176 then # Alive only if previously alive.177 return $ALIVE178 fi179180 return $DEAD # Default.181182 }183184185 GetCount () # Count live cells in passed cell's neighborhood.186 # Two arguments needed:187 # $1) variable holding array188 # $2) cell number189 {190 local cell_number=$2191 local array192 local top193 local center194 local bottom195 local r196 local row197 local i198 local t_top199 local t_cen200 local t_bot201 local count=0202 local ROW_NHBD=3203204 array=( `echo "$1"` )205206 let "top = $cell_number - $COLS - 1" # Set up cell neighborhood. 207 let "center = $cell_number - 1"208 let "bottom = $cell_number + $COLS - 1"209 let "r = $cell_number / $COLS"210211 for ((i=0; i<$ROW_NHBD; i++)) # Traverse from left to right.212 do213 let "t_top = $top + $i"214 let "t_cen = $center + $i"215 let "t_bot = $bottom + $i"216217218 let "row = $r" # Count center row of neighborhood.219 IsValid $t_cen $row # Valid cell position?220 if [ $? -eq "$TRUE" ]221 then222 if [ ${array[$t_cen]} = "$ALIVE1" ] # Is it alive?223 then # Yes?224 let "count += 1" # Increment count.225 fi226 fi227228 let "row = $r - 1" # Count top row. 229 IsValid $t_top $row230 if [ $? -eq "$TRUE" ]231 then232 if [ ${array[$t_top]} = "$ALIVE1" ]233 then234 let "count += 1"235 fi236 fi237238 let "row = $r + 1" # Count bottom row.239 IsValid $t_bot $row240 if [ $? -eq "$TRUE" ]241 then242 if [ ${array[$t_bot]} = "$ALIVE1" ]243 then244 let "count += 1"245 fi246 fi247248 done249250251 if [ ${array[$cell_number]} = "$ALIVE1" ]252 then253 let "count -= 1" # Make sure value of tested cell itself 254 fi #+ is not counted.255256257 return $count258259 }260261 next_gen () # Update generation array.262 {263264 local array265 local i=0266267 array=( `echo "$1"` ) # Convert passed arg to array.268269 while [ "$i" -lt "$cells" ]270 do271 IsAlive "$1" $i ${array[$i]} # Is cell alive?272 if [ $? -eq "$ALIVE" ]273 then # If alive, then274 array[$i]=. #+ represent the cell as a period. 275 else276 array[$i]="_" # Otherwise underscore277 fi #+ (which will later be converted to space).278 let "i += 1"279 done280281282 # let "generation += 1" # Increment generation count.283 # Why was the above line commented out?284285286 # Set variable to pass as parameter to "display" function.287 avar=`echo ${array[@]}` # Convert array back to string variable. 288 display "$avar" # Display it.289 echo; echo290 echo "Generation $generation - $alive alive"291292 if [ "$alive" -eq 0 ]293 then294 echo295 echo "Premature exit: no more cells alive!"296 exit $NONE_ALIVE # No point in continuing297 fi #+ if no live cells.298299 }300301302 # =========================================================303304 # main ()305306 # Load initial array with contents of startup file.。
Shell脚本实践
Shell脚本实践1. 脚本判断命令输出是否为空(1)判断字符串为空 if [ "$str" = "" ] if [ x"$str" = x ] if [ -z "$str" ] (-n 为⾮空) 注意:都要代双引号,否则有些命令会报错,养成好习惯吧! 2.输⼊y/n 可以使⽤判断符号进⾏数据的判断,如检查某变量是否为空 [ -z $SHELL ],需要注意的是中括号(“[]”)内的组件必须以空格隔开。
有以下脚本:#!/bin/bashread -p "input you choice(y/n):" choice[ "$choice" == "y" ] || [ "$choice" == "Y" ] && echo "OK,continue" && exit 0[ "$choice" == "n" ] || [ "$choice" == "N" ] && echo "Oh,interrupt!" && exit 0echo "I don't know what is your choice" && exit 0#! /bin/shecho "Is it morning? Please answer yes or no."read YES_OR_NOif [ "$YES_OR_NO" = "yes" ]; thenecho "Good morning!"elif [ "$YES_OR_NO" = "no" ]; thenecho "Good afternoon!"elseecho "Sorry, $YES_OR_NO not recognized. Enter yes or no."exit 1fiexit 0(3)while条件循环和C语⾔类似。
常用的Shell实用脚本
常⽤的Shell实⽤脚本1.检测两台服务器指定⽬录下的⽂件的⼀致性#!/bin/bash######################################检测两台服务器指定⽬录下的⽂件⼀致性######################################通过对⽐两台服务器上⽂件的md5值,达到检测⼀致性的⽬的dir=/data/webb_ip=192.168.88.10#将指定⽬录下的⽂件全部遍历出来并作为md5sum命令的参数,进⽽得到所有⽂件的md5值,并写⼊到指定⽂件中find $dir -type f|xargs md5sum > /tmp/md5_a.txtssh $b_ip "find $dir -type f|xargs md5sum > /tmp/md5_b.txt"scp $b_ip:/tmp/md5_b.txt /tmp#将⽂件名作为遍历对象进⾏⼀⼀⽐对for f in `awk '{print 2}' /tmp/md5_a.txt`do#以a机器为标准,当b机器不存在遍历对象中的⽂件时直接输出不存在的结果if grep -qw "$f" /tmp/md5_b.txtthenmd5_a=`grep -w "$f" /tmp/md5_a.txt|awk '{print 1}'`md5_b=`grep -w "$f" /tmp/md5_b.txt|awk '{print 1}'`#当⽂件存在时,如果md5值不⼀致则输出⽂件改变的结果if [ $md5_a != $md5_b ]thenecho "$f changed."fielseecho "$f deleted."fidone##diff -y a.txt b.txt2.扫描主机端⼝状态#!/bin/bashHOST=$1PORT="22 25 80 8080"for PORT in $PORT; doif echo &>/dev/null > /dev/tcp/$HOST/$PORT; thenecho "$PORT open"elseecho "$PORT close"fidone3.Expect实现SSH免交互执⾏命令Expect是⼀个⾃动交互式应⽤程序的⼯具,如telnet,ftp,passwd等。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
很实用的Shell脚本(实践版)/erpHome/shell/old/$1/$2.zip.oldfind . -mtime +7 | xargs nice -n 20 zip -qm /erpHome/shell/old/$1/$2_$DayOfWeek.zip # find . -mtime +7FiarchiveOld2.sh. /erpHome/shell/setP.shexport DayOfWeek=`date +"%u"`if test "$#" -lt 1 || test -z "$1"thenecho At least one argument needed.exitfiif test ! -e "$ShellHome/old/$1"thencd $ShellHome/old/mkdir -p $1fiif test ! -e "$ERPHome/$1"thenecho "$ERPHome/$1" "does not exist" exitficd $ERPHome/$1mv $ShellHome/old/$1_$DayOfWeek.zip $ShellHome/old/$1.zip.oldfind . -mtime +7 -type f | xargs nice -n 20 zip -qm $ShellHome/old/$1_$DayOfWeek.zip #find . -mtime +7 -type farchiveOldAll.sh/erpHome/shell/archiveOld.shwork/dr/engine jrprint/erpHome/shell/archiveOld.sh work/de tmp /erpHome/shell/archiveOld2.sh publicbackupLog.shecho `date` ": Backup the logs". /erpHome/shell/setP.shcd $ERPHome/waslogsmkdir old/mv std*_*.txt old/mv $LOGHome/LOG_$DD.zip $LOGHome/LOG.zip.oldzip -qmr $LOGHome/LOG_$DD.zip `ls $ERPHome/waslogs | grep -Ev "std|FATAL_DEBUG.xml"`ls -l $LOGHome/LOG_$DD.zipecho `date` ": Backup the logs done."backupWASAll.sh. /erpHome/shell/setP.shcd /erpHome#rename old backup fileecho "####" `date` "ERP program backup ####" #mv /wasbackup/WASBackup_"$DayOfWeek".tar /wasbackup/WASBackup_old.tarrm -Rf /wasbackup/erpbak/WASBackup_"$DayOfWeek". tar#backup ERP programnice -n 20 tar -cf /wasbackup/erpbak/WASBackup_"$DayOfWeek". tar jln.ear/erp.war DIClient DIServer ThreadPool erpdatals -l /wasbackup/erpbak/WASBackup_"$DayOfWeek". tarcollectAudit.sh. /erpHome/shell/setP.sh jlnaudit shutdownauditpr -v < /audit/trail | grep PROC_Execute > $LOGHome/AUDIT_$YYMMDD.txt mv /audit/trail $LOGHome/trail_$TTgzip $LOGHome/trail_$TTaudit startlast | grep "$TT2" >$LOGHome/LOGIN_$YYMMDD.txtgrep "$TT3" /var/adm/sulog > $LOGHome/SU_$YYMMDD.txtcplogs.shexport dd=`perl -e '@y=localtime(time()-86400); printf "%02d\n",$y[3];'`cd /erpHome/shell/logsmkdir /test/erplogscp ./LOG_"$dd".zip /test/erplogscpnmon.shcd /worktmp/nmonexport dd=`perl -e '@y=localtime(time()-86400); printf "%02d\n",$y[3];'`export d=`date +%y%m`"$dd"export HOSTNAME=`hostname`export data="$HOSTNAME"_"$d"_"*"ftp -n <<EOFopen 10.32.1.138user nmon nmoncd $HOSTNAMEput $databyeEOFddd.shcd $1touch 11.txtfilter.awk BEGIN {DiscardURLs="/erp/de/deCommand/erp/jsp/"DiscardAmount=split(DiscardURLs,DiscardUR L," ")ResponseThreshold=4.9999nlines=0totalCount=0}function extractTime(myDate,aSize){if (aSize==2) return myDate[2]if (myDate[2]=="上午") return myDate[3]split(myDate[3],dates,":")return dates[1]+12 ":" dates[2] ":" dates[3]}function isSkip(myURL) {for (i = 1; i <= DiscardAmount; i++)if (index(myURL,DiscardURL[i])>0) return 1return 0}{if (isSkip($3)==0) {if (NF==10){totalCount++;if ($4 > ResponseThreshold){mySize=split($2,myDate," ")myTime=extractTime(myDate,mySize)print $1 "\t" myTime "\t" $3 "\t" $4 "\t" $5 "\t" $6 nlines++ }}}} END{print "本日网页执行总次数:" totalCount " (JSP,servlet,但不包含图片等静态网页,也不包含/erp/jsp/开头的这些监控画面)"print "共 " nlines " 笔异常资料"formatHTML.awkBEGIN {}function getSysName(myURL) {fCount=split(myURL,myArray,"/") return myArray[3]}functiongetMaxInArray(oArray,oResult,oIndex){maxValue=0for (idx in oCount){if(oCount[idx]>maxValue){maxValue=oCount[idx]maxSys=idx}}delete oArray[maxSys]oResult[oIndex,1]=maxSysoResult[oIndex,2]=maxValue}function sort(array,result,thresHold){ for(i=1;i<=5;i++){getMaxInArray(array,result,i)}}{oSys=getSysName($3)if (NF!=6){print $0 "<br/>"}else{oCount[oSys]++oRecord++;print "<tr style='background-color:#C4DAFF'><td>" $1 "</td><td>" $2 "</td><td>" $3 "</td><td>" $4 "</td><td>" $5 "</td><td>" $6 "</td></tr>"}} END{oThreshold oRecord/10sort(oCount,oResult,oThreshold)print "</table>"print "<script>"max=oResult[1,2]for(i=1;i<=5;i++){print "addData(\"" (oResult[i,2]/max*100) "pt\"," i ",\"" oResult[i,1] "\",\"" oResult[i,2] "\")" }}formatHTML.awk.oldBEGIN {print "<html><head><meta http-equiv='Content-Type'content='text/html;charset=GBK'><style>td {border:1px solid black;}</style></head><body><H1 align>执行时间超过60 秒的网址</H1><table style='border:1px solid black' cellspacing=0 align=center>"}if (NF!=6){print $0 "<br/>"}else if (NR==1){print "<tr style='background-color:pink'align=center><td>" $1 "</td><td>" $2 "</td><td>" $3 "</td><td>" $4 "</td><td>" $5 "</td><td>" $6 "</td></tr>"} else{print "<tr style='background-color:#C4DAFF'><td>" $1 "</td><td>" $2 "</td><td>" $3 "</td><td>" $4 "</td><td>" $5 "</td><td>" $6 "</td></tr>"}} END{print "</table></body></html>"}htmlFoot.txt</script></body></html>htmlHead.txt<html><head><meta http-equiv='Content-Type' content='text/html; charset=GBK'><style>@import "/erp/html/dn/filtergrid.css";.td2 {border:0px}.td3 {border-right}.div1 {border:solid black 1px}.div2 {border:solid black 1px;text-align:right}.div3 {border:solid 1px white}td {border:1px solid black;}</style><script language="javascript" type="text/javascript"src="/erp/html/dn/actb.js"></script><!-- External script --><script language="javascript" type="text/javascript"src="/erp/html/dn/tablefilter.js"></scrip t><script language="javascript" type="text/javascript">function doFilter(){var props = {remember_grid_values: true,alternate_rows: true,rows_counter: true,rows_counter_text: "Displayed rows: ",btn_reset: true,btn_reset_text: "Clear", btn_text: " > ",loader: true,loader_text: "Filtering data...",col_0: "select",col_1: "none",col_3: "none",col_4: "none",col_5: "select",display_all_text: "< Show all >",sort_select: true}setFilterGrid("table1",props);}</script><script>var Colors=newArray("green","red","blue","yellow","oran ge")functionaddData(oWidth,oIndex,oSys,oData){chartBlock.innerHTML+="<div class=div3 style='background-color:"+Colors[(oIndex%5)] +";width="+ oWidth +"'></div>";sysBlock.innerHTML+="<div class='div1'>"+ oSys +"</div>";dataBlock.innerHTML+="<divclass='div2'>"+ oData +"</div>";}function doVisible(){if (vf1.innerText=="+"){ vf1.innerText="-";chartBlock.style.visibility="visible";sysBlock.style.visibility="visible";dataBlock.style.visibility="visible";}else {vf1.innerText="+";chartBlock.style.visibility="hidden"; sysBlock.style.visibility="hidden";dataBlock.style.visibility="hidden";}}</script></head><body><TABLE cellspacing=0 cellpadding=0><TR><TD width=100% class=td2><H1 align>执行时间超过 5 秒的网址</H1></TD><div id=myChart style="border:black solid 1px"><TD class=td3 id=chartBlock style="visibility:hidden"></TD><TD class=td2 id=sysBlock style="visibility:hidden"></TD><TD class=td2 id=dataBlock style="visibility:hidden"><td id=vf1 UNSELECTABLE=on style="cursor:hand"onclick="doVisible()">+</td></div></TD></TR></TABLE><BUTTON UNSELECTABLE=on style="cursor:hand"onclick="doFilter()">Filter</BUTTON><table id=table1 style='border:1px solid black' cellspacing=0 align=center><trstyle='background-color:pink'align=center><td>来源电脑</td><td>时间</td><td>网址</td><td>执行时间</td><td>QueryString</td><td>UserID</td></tr>increaseERP.sh. /erpHome/shell/setP.shcd /erpHomefind jln.ear -type f -mtime 2 -print >/tmp/filelist.txtfind erpdata -type f -mtime 2 -print >>/tmp/filelist.txttar cvfL/wasbackup/WASBackup_"$DayOfWeek".tar/tmp/filelist.txtnight.old. /erpHome/shell/setP.sh$ShellHome/backupLog.sh >> $NightLog 2>&1 $ShellHome/ApacheLogRotate.sh >> $NightLog 2>&1mv /erpHome/bx.ear/erp.war/access.txt /erpHome/shell/logs/access_$YYMMDD.txt awk -F "\t" -f /erpHome/shell/filter.awk /erpHome/shell/logs/access_$YYMMDD.txt > /erpHome/shell/logs/temp.csv#echo "ㄓ方筿福,丁,呼,磅︽丁,QueryString,UserID" > /erpHome/shell/logs/temp2.csvecho "来源电脑,时间,网址,执行时间,QueryString,UserID" > /erpHome/shell/logs/temp2.csvsort -t "," +3 -n -r /erpHome/shell/logs/temp.csv >> /erpHome/shell/logs/temp2.csvawk -F "," -f /erpHome/shell/formatHTML.awk /erpHome/shell/logs/temp2.csv > $ERPHome/public/$YYMMDD.htmlgzip -v /erpHome/shell/logs/access_$YYMMDD.txt >> $NightLog 2>&1sv#awk -f /erpHome/shell/filter.awk /erpHome/shell/logs/access_$YYMMDD.txt > $ERPHome/public/$YYMMDD.html#gzip -v /erpHome/shell/logs/access_$YYMMDD.txt >> $NightLog 2>&1night.sh. /erpHome/shell/setP.sh#/usr/WebSphere/AppServer/bin/stopServer. sh server1 >> $NightLog 2>&1$ShellHome/backupLog.sh >> $NightLog 2>&1 $ShellHome/ApacheLogRotate.sh >> $NightLog 2>&1#$ShellHome/processFile.sh db_serv2 0000 >> $NightLog 2>&1#mv $ERPHome/access.txt /erpHome/shell/logs/access_$YYMMDD.txt awk -F "\t" -f /erpHome/shell/filter.awk /erpHome/shell/logs/access_$YYMMDD.txt > /erpHome/shell/logs/temp.csvsort +3 -n -r /erpHome/shell/logs/temp.csv > /erpHome/shell/logs/temp2.csvcat /erpHome/shell/htmlHead.txt > $ERPHome/public/$YYMMDD.htmlawk -F "\t" -f /erpHome/shell/formatHTML.awk/erpHome/shell/logs/temp2.csv >> $ERPHome/public/$YYMMDD.htmlcat /erpHome/shell/htmlFoot.txt >> $ERPHome/public/$YYMMDD.html#gzip -v /erpHome/shell/logs/access_$YYMMDD.txt >> $NightLog 2>&1/erpHome/shell/archiveOldAll.sh >> $NightLog 2>&1#/usr/WebSphere/AppServer/bin/startServer .sh server1 >> $NightLog 2>&1night.sh.bak. /erpHome/shell/setP.sh#/usr/WebSphere/AppServer/bin/stopServer. sh server1 >> $NightLog 2>&1$ShellHome/backupLog.sh >> $NightLog 2>&1 $ShellHome/ApacheLogRotate.sh >> $NightLog 2>&1#$ShellHome/processFile.sh db_serv2 0000 >> $NightLog 2>&1#mv $ERPHome/access.txt /erpHome/shell/logs/access_$YYMMDD.txt#awk -F "\t" -f /erpHome/shell/filter.awk /erpHome/shell/logs/access_$YYMMDD.txt > /erpHome/shell/logs/temp.csv#sort +3 -n -r /erpHome/shell/logs/temp.csv > /erpHome/shell/logs/temp2.csv#cat /erpHome/shell/htmlHead.txt > $ERPHome/public/$YYMMDD.html#awk -F "\t" -f/erpHome/shell/formatHTML.awk/erpHome/shell/logs/temp2.csv >> $ERPHome/public/$YYMMDD.html#cat /erpHome/shell/htmlFoot.txt >> $ERPHome/public/$YYMMDD.htmlgzip -v /erpHome/shell/logs/access_$YYMMDD.txt >> $NightLog 2>&1/erpHome/shell/archiveOldAll.sh >> $NightLog 2>&1#/usr/WebSphere/AppServer/bin/startServer .sh server1 >> $NightLog 2>&1#Old.馵..@public!IHS.old.zip'public.zip.old#pu blic_5.zip$public_7.zip*public_1.zip%publ ic_2.zip&public_4.zip(public_6.zip)shell_ test.zipwork"public_3.zipxjh@p55013:/erpHome/shell#processFile.shexport YYMM=`/usr/bin/date +"%y%m"`; export YYMMexport YYMMDD=`/usr/bin/date +"%y%m%d"`; export YYMMDDmkdir -p /nmon/report/$1/$YYMM/$YYMMDD/ cd /nmonnice -n 20 ./nmon2rrd -f $1_"$YYMMDD"_$2.nmon -d /nmon/report/$1/$YYMM/$YYMMDD -xgzip -9 /nmon/report/$1/$YYMM/$YYMMDD/*rrd*gzip -9 $1_"$YYMMDD"_$2.nmonres.sh/erpHome/shell/stopServer.sh $1 /erpHome/shell/startServer.sh $1restartjvm.sh/usr/WebSphere/AppServer/profiles/AppSrv0 1/bin/stopServer.sh s1/usr/WebSphere/AppServer/profiles/AppSrv0 1/bin/startServer.sh s1#/usr/WebSphere/AppServer/profiles/AppSrv 01/bin/stopServer.sh s2#/usr/WebSphere/AppServer/profiles/AppSrv 01/bin/startServer.sh s2rmGClog.shcd/usr/WebSphere/AppServer/profiles/AppSrv0 1/logs/s1> native_stderr.logcd/usr/WebSphere/AppServer/profiles/AppSrv0 1/logs/s2> native_stderr.logcd/usr/WebSphere/AppServer/profiles/AppSrv0 1/logs/t1> native_stderr.logcd/usr/WebSphere/AppServer/profiles/AppSrv0 1/logs/t2rmwasbackup.shcd /wasbackupfind . -ctime +1 -exec rm {} \;server.lstserver1setP.shexport ERPHome=/erpHome/jln.ear/erp.warif ! test -e $ERPHomethenecho "Warning! " $ERPHome " not exists."exitfiexport ShellHome=/erpHome/shellexport LOGHome=/erpHome/shell/logsexport WAS_HOME=/usr/WebSphere/AppServer export Java_Home=$WAS_HOME/java/export TT=`date +"%Y%m%d%H%M%S"`export TT2=`date +"%b %d"`export TT3=`date +"%m/%d"`export YYMMDD=`date +"%Y%m%d"`export DD=`date +"%d"`exportUpdateLog=$LOGHome/update_$YYMMDD.txt exportNightLog=$LOGHome/night_$YYMMDD.txt export DayOfWeek=`date +"%u"`startAllService.sh/usr/WebSphere/IHS/bin/apachectl start /erpHome/ThreadPool/bin/go.sh start/erpHome/DIServer/bin/go.sh start/usr/WebSphere/AppServer/bin/startServer. sh server1startServer.sh#! /usr/bin/kshif test "$#" -lt 1 || test -z "$1"thenecho Usage: $0 [ServerName]echo "Available ServerName: "awk '{print "\t\t\t" $1}' /erpHome/shell/server.lstexitfiIFSsave=$IFSwhile IFS=''; read linedoif test $1 = $linethenexport ValidArg=1breakfidone < /erpHome/shell/server.lstIFS=$IFSsaveif test -z "$ValidArg"thenecho Invalid ServerName. echo "Available ServerName: "awk '{print "\t\t\t" $1}' /erpHome/shell/server.lstexitfiexport ServerName=$1echo "#################### start $1 `date` ####################" >> /erpHome/shell/logs/serverRestart.log/usr/WebSphere/AppServer/bin/startServer. sh $1stopServer.sh#! /usr/bin/kshif test "$#" -lt 1 || test -z "$1"thenecho Usage: $0 [ServerName]echo "Available ServerName: "awk '{print "\t\t\t" $1}' /erpHome/shell/server.lstexitfiIFSsave=$IFSwhile IFS=''; read linedoif test $1 = $linethenexport ValidArg=1 breakfidone < /erpHome/shell/server.lstIFS=$IFSsaveif test -z "$ValidArg"thenecho Invalid ServerName. echo "Available ServerName: "awk '{print "\t\t\t" $1}' /erpHome/shell/server.lstexitfiexport ServerName=$1echo "#################### stop $1 `date` ####################" >> /erpHome/shell/logs/serverRestart.log/usr/WebSphere/AppServer/bin/stopServer.s h $1syncConfig.shcp/erpHome/jln.ear/erp.war/WEB-INF/web.xm l/usr/WebSphere/AppServer/profiles/Dmgr01/ config/cells/p55013Cell01/applications/jl n.ear/deployments/jln/erp.war/WEB-INF/erpHome/jln.ear/erp.war/WEB-INF/web.xm l/usr/WebSphere/AppServer/profiles/AppSrv0 1/config/cells/p55013Cell01/applications/ jln.ear/deployments/jln/erp.war/WEB-INF /usr/WebSphere/AppServer/profiles/Dmgr01/ bin/GenPluginCfg.shsyncConfig.sh.bakcp/erpHome/jln.ear/erp.war/WEB-INF/web.xm/usr/WebSphere/AppServer/profiles/Dmgr01/ config/cells/p510Cell01/applications/jln. ear/deployments/jln/erp.war/WEB-INFcp/erpHome/jln.ear/erp.war/WEB-INF/web.xm l/usr/WebSphere/AppServer/profiles/AppSrv0 1/config/cells/p510Cell01/applications/jl n.ear/deployments/jln/erp.war/WEB-INF/usr/WebSphere/AppServer/profiles/Dmgr01/ bin/GenPluginCfg.shupdateFTPSrc.sh. /erpHome/shell/setP.shecho `date` > $ERPHome/work/da/log/update/last.log export DAHome=/home/ftpuser/pubif ! test $(find $DAHome -type f | wc -l) -eq 0thenecho `date` ": Update source" >> $UpdateLog 2>&1echo "################ Update the source ################" >> $UpdateLog 2>&1echo $ERPHome >> $UpdateLog 2>&1/usr/bin/cp -r $DAHome/* $ERPHome >> $UpdateLog 2>&1# /usr/bin/cp -r $DAHome/* /erpHome/shell/src >> $UpdateLog 2>&1# /usr/bin/rm -fre $DAHome/* >> $UpdateLog 2>&1find $DAHome -type f -exec \rm -e {} \; >> $UpdateLog 2>&1# echo "copy" >> $UpdateLog 2>&1# mail -s "$1 update program" root < $UpdateLogecho `date` ": Update source done" >> $UpdateLog 2>&1fiupdateSource.sh. /erpHome/shell/setP.sh $ShellHome/updateSrc.sh bin $ShellHome/updateSrc.sh toc $ShellHome/updateFTPSrc.sh。