Shell脚本-Demo-29例
shell循环详解及实例

shell循环详解及实例⼀、条件选择、判断(if、case)1.1 if语句⽤法及实例当我们在脚本中遇到需要判断的时候,我们就可以⽤if语句来实现。
具体的语法如下:单分⽀if 判断条件;then 条件为真的分⽀代码 fi双分⽀if 判断条件; then条件为真的分⽀代码else条件为假的分⽀代码fi多分⽀if 判断条件1; then条件为真的分⽀代码elif 判断条件2; then条件为真的分⽀代码elif 判断条件3; then条件为真的分⽀代码else以上条件都为假的分⽀代码fi在多分⽀中,系统会逐条判断你写⼊的条件,第⼀次遇到“真”条件时,执⾏该分⽀,⽽后结束整个if语句。
注意:1、if和fi是成对出现的2、if语句可以嵌套。
Example:1)判断两个数字的⼤⼩1 #!/bin/bash2 #定义变量3 read -p "Please input the first num:" num14 read -p "Please input the second num:" num25 #判断数字是否符合标准6 if [[ $num1 =~ ^[0-9]+$ && $num2 =~ ^[0-9]+$ ]];then7 # 判断两个数字的⼤⼩并输出判断结果8 if [ $num1 -lt $num2 ];then9 echo "The num2 is biger than the num1"10 elif [ $num1 -eq $num2 ];then11 echo "Two numbers equal"12 else13 echo "The num1 is biger than the num2"14 fi15 else16 echo "Please enter the correct number"17 fi1819 #删除变量20 unset num1 num22)编写脚本/root/bin/createuser.sh,实现如下功能:使⽤⼀个⽤户名做为参数,如果指定参数的⽤户存在,就显⽰其存在,否则添加之;显⽰添加的⽤户的id号等信息1 #!/bin/bash2 #定义变量3 read -p "请输⼊⼀个⽤户名:" name4 #判断⽤户名是否存在5 if `id $name &> /dev/null`;then6 # 若存在,则输出ID等信息7 echo "⽤户存在,⽤户的ID信息为:`id $name`"8 else9 # 若不存在,则添加⽤户,设置密码为随机8位,下次登录时提⽰修改密码,同时显⽰ID等信息10 passwd=`cat /dev/urandom |tr -cd [:alpha:] |head -c8`11 `useradd $name &> /dev/null`12 `echo "$passwd" | passwd --stdin $name &> /dev/null`13 echo "⽤户名:$name 密码: $passwd" >> user.txt14 `chage -d 0 $name`15 echo "⽤户已添加,⽤户的ID信息为:`id $name` 密码为:$passwd"16 fi1718 #删除变量19 unset name passwd1.2 case⽤法及实例当涉及到多个条件匹配的时候,我们⽤if可能就很⿇烦了,这个时候,我们就可以⽤case来编写这个脚本。
Shell 经典实例

Thizlinux 系统教程 Shell 经典实例----------------Milo经典小shell1 列目录树的shell脚本如下:#!/bin/sh# dtree: Usage: dtree [any directory]dir=${1:-.}(cd $dir; pwd)find $dir -type d -print | sort -f | sed -e "s,^$1,," -e "/^$/d" -e "s,[^/]*/([^/]*)$,`----1," -e "s,[^/]*/,| ,g"2 while中使用read (file是一个文件)cat file | while read linedoecho $lineecho " :: Please input any key(s):c"str4read=""while truedochr4read=`dd if=/dev/tty bs=1 count=1 2>/dev/null`str4read=$str4read$chr4readif [ "$chr4read" = "" ] ;then break; fidoneecho " :: |$str4read|"done3 将多个空格替换为字符sed 's/[ ][ ]*/ /g'如果空格与tab共存时用sed -e 's/[[:space:]][[:space:]]*/ /g' filename4用脚本实现分割文件#!/bin/bashif [ $# -ne 2 ]; thenecho 'Usage: split file size(in bytes)'exitfifile=$1size=$2if [ ! -f $file ]; thenecho "$file doesn't exist"exitfi#TODO: test if $size is a valid integerfilesize=`/bin/ls -l $file | awk '{print $5}'` echo filesize: $filesizelet pieces=$filesize/$sizelet remain=$filesize-$pieces*$sizeif [ $remain -gt 0 ]; thenlet pieces=$pieces+1fiecho pieces: $piecesi=0while [ $i -lt $pieces ];doecho split: $file.$i:dd if=$file of=$file.$i bs=$size count=1 skip=$i let i=$i+1doneecho "#!/bin/bash" > mergeecho "i=0" >> mergeecho "while [ $i -lt $pieces ];" >> mergeecho "do" >> mergeecho " echo merge: $file.$i" >> mergeecho " if [ ! -f $file.$i ]; then" >> mergeecho " echo merge: $file.$i missed" >> mergeecho " rm -f $file.merged" >> mergeecho " exit" >> mergeecho " fi" >> mergeecho " dd if=$file.$i of=$file.merged bs=$size count=1 seek=$i" >> merge echo " let i=$i+1" >> mergeecho "done" >> mergechmod u+x merge'5得到上月未日期,格式为YYYYMMDDget_lastday_of_lastmonth(){yy=`date +%Y`mm=`date +%m-1|bc`[ $mm -lt 1 ] && mm=12;yy=`expr $yy - 1`aaa=`cal $mm $yy`dd=`echo $aaa|awk '{print $NF}'`echo $yy$mm$dd}print $NF的$NF是打印最后一个列。
经典shell 脚本实例

fi
done
#!/bin/bash
if [ $# -le 0 ]
then
echo "Not enough parameters"
exit 1
fi
#string="2 3 4 5 6"
#set string
sum=0
while [ $# -gt 0 ]
do
sum=`expr $sum + $1`
shift
印出该数值,然后再次要求用户输入数值。直到用户输入"end"停止。#!/bin/sh
unset var
while [ "$var" != "end" ]
do
echo -n "please input a number: "
ቤተ መጻሕፍቲ ባይዱ
read var
if [ "$var" = "end" ]
then
break
fi
Linux shell 脚本实例
1. 写一个脚本,利用循环计算 10 的阶乘#!/bin/sh
factorial=1
for a in `seq 1 10`
do
factorial=`expr $factorial \* $a`
done
echo "10! = $factorial"
2. 写一个脚本,执行后,打印一行提示“Please input a number:",要求用户输入数值,然后打
esac done #! /bin/sh a=10 b=20 c=30 value1=`expr $a + $b + $c` echo "The value of value1 is $value1" value2=`expr $c / $b` echo "The value of value2 is $value2" value3=`expr $c * $b` echo "The value of value3 is $value3" value4=`expr $a + $c / $b` echo "The value of value4 is $value4" var4=`expr $value4 - $value2` echo $var4
shell脚本编程(完结版)

if [ 条件表达式 2 ] then …… …… else …… …… fi
命令串; else
命令串; fi
如有任何疑问,请联系作者,作者 QQ:1028150787,或者到韦脚本编程学习笔记 2013 年 5 月 2 日 追风~忆梦
1. 整数测试运算
test int1 -eq int2: 判断两个数是否相等 test int1 -ne int2: 判断两个数是否不相等 test int1 -gt int2: 判断整数 1 是否大于整数 2 test int1 -ge int2: 判断整数 1 是否大于等于整数 2 test int1 -lt int2: 判断整数 1 是否小于整数 2 test int1 -le int2: 判断整数 1 是否小于等于整数 2 整数测试也可以使用 let 命令或双圆括号 相关操作为:== 、!= 、> 、>= 、< 、<= 如: x=1; [ $x -eq 1 ]; echo $? x=1; let "$x == 1"; echo $? x=1; (($x+1>= 2 )); echo $? 两种测试方法的区别: 使用的操作符不同 let 和 双圆括号中可以使用算术表达式,而中括号不能 let 和 双圆括号中,操作符两边可以不留空格
1. 整数测试运算 .................................................4 2. 字符串测试运算 ...............................................4 3. 文件测试运算 .................................................5 4. 逻辑运算 .....................................................5 第二节 在 shell 脚本中进行条件控制 ................................ 5 第三节 在 shell 脚本中进行 for 循环 ................................ 7 第四节 在 shell 脚本中进行 while 循环 .............................. 8 第五节 在 shell 脚本中使用 util 循环 ............................... 8 第六节 在 shell 脚本中使用函数 .................................... 8 第七节 shell 脚本之 echo 和 expr 讲解 ................................ 9 第八节 shell 脚本循环终止之 break 和 continue ..................... 10 第九节 shell 脚本之 exit 和 sleep ................................. 11 第十节 shell 脚本之 select 循环与菜单 ............................. 11 第十一节 shell 脚本之循环控制 shift 命令 .......................... 11 第十二节 shell 脚本之字符串操作 ................................... 11 第十三节 shell 脚本之数组实现 ..................................... 12 第十四节 shell 脚本之脚本调试 ..................................... 12 第十五节 shell 脚本之编程小结 ..................................... 12 程序例程 ......................................................... 14 习题实训 ......................................................... 29 综合实例 ......................................................... 31 1. 需求分析....................................................31 2.系统设计 ....................................................31 3.程序代码 ....................................................31 声明 ............................................................. 35
shell脚本常用命令

shell脚本常⽤命令shell基本命令1.#!/bin/sh是指此脚本使⽤/bin/sh来解释执⾏。
解释:#! 是⼀个约定的标记,它告诉系统这个脚本需要什么解释器来执⾏,即使⽤哪⼀种 Shell。
2.echo 命令⽤于向窗⼝输出⽂本。
举例:echo "Hello World !"3.your_name="qinjx"赋值变量echo ${your_name}打印变量;使⽤变量的时候加括号和美元符4.chmod +x ./test.sh #使脚本具有执⾏权限./test.sh #执⾏脚本chmod 777 /tmp -R 意思是把tmp⽂件夹及其⼦bai⽂件夹的权限全部修改为777解释语句⼀:ping -c 5 > /dev/null 2>&11. ping -c 5 -c<完成次数>:设置完成要求回应的次数;2. >/dev/null这条命令的作⽤是将标准输出1重定向到/dev/null中。
/dev/null代表linux的空设备⽂件,所有往这个⽂件⾥⾯写⼊的内容都会丢失,俗称“⿊洞”。
那么执⾏了>/dev/null之后,标准输出就会不再存在,没有任何地⽅能够找到输出的内容。
3. 2>&1这条命令⽤到了重定向绑定,采⽤&可以将两个输出绑定在⼀起。
这条命令的作⽤是错误输出将和标准输出同⽤⼀个⽂件描述符,说⼈话就是错误输出将会和标准输出输出到同⼀个地⽅。
linux在执⾏shell命令之前,就会确定好所有的输⼊输出位置,并且从左到右依次执⾏重定向的命令,所以>/dev/null 2>&1的作⽤就是让标准输出重定向到/dev/null中(丢弃标准输出),然后错误输出由于重⽤了标准输出的描述符,所以错误输出也被定向到了/dev/null中,错误输出同样也被丢弃了。
执⾏了这条命令之后,该条shell命令将不会输出任何信息到控制台,也不会有任何信息输出到⽂件中。
常用shell脚本指令

常用shell脚本命令1、显示包含文字aaa的下一行的内容:sed -n '/aaa/{n;p;}' filename2、删除当前行与下一行的内容:sed -i '/aaa/{N;d;}' filename3、删除当前行与下两行的内容:sed -i '/aaa/{N;N;d;}' filename依次类推,删除三行,则为{N;N;N;d;},分析知:N为next4、得出以空格为分割的字符串中单词的个数,即统计个数:awk ' { print NF } '如显示字符串VALUE中的单词个数,其中VALUE为:aaa bbb ccc ddd ee f则执行 echo $VALUE | awk ' { print NF } ' 后的结果为65、在linux中建立一个文件与另一文件的链接,即符号链接ln -s /var/named/chroot/etc/named.conf named.conf这要就建立了当前目录的文件named.conf对/var/named/chroot/etc/named.conf 的符号链接。
即操作named.conf就意味着操作实际文件/var/named/chroot/etc/named.conf ,这时用ll命令查看的结果如:lrwxrwxrwx 1 root root 32 Mar 22 12:29 named.conf ->/var/named/chroot/etc/named.conf注意:当用sed来通过named.conf来删除一部分信息时,会将符号链接的关系丢掉,即会将named.conf变成一个实际文件。
所以需对实际文件进行删除操作。
6、显示指定字符范围内的内容:如:显示文件test.txt中字符#test begin与#test end之间所有的字符sed -n "/#test begin/,/#test end/p" test.txt或 awk "/#test begin/,/#test end/" test.txt在日常系统管理工作中,需要编写脚本来完成特定的功能,编写shell脚本是一个基本功了!在编写的过程中,掌握一些常用的技巧和语法就可以完成大部分功能了,也就是2/8原则.1. 单引号和双引号的区别单引号与双引号的最大不同在于双引号仍然可以引用变量的内容,但单引号内仅是普通字符,不会作变量的引用,直接输出字符窜。
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 Script,Shell与Windows/Dos下的相似,也就是⽤各类命令预先放⼊到⼀个⽂件中,⽅便⼀次性执⾏的⼀个,主要是⽅便进⾏设置或者管理⽤的。
但是它⽐Windows下的批处理更强⼤,⽐⽤其他编程的程序效率更⾼,毕竟它使⽤了Linux/Unix下的命令。
换⼀种说法也就是,shell script是利⽤shell的功能所写的⼀个程序,这个程序是使⽤,将⼀些shell的语法与指令写在⾥⾯,然后⽤正规表⽰法,管线命令以及数据流重导向等功能,以达到我们所想要的处理⽬的shell和shell脚本的区别:shell是什么呢?确切⼀点说,Shell就是⼀个,它的作⽤就是遵循⼀定的语法将输⼊的命令加以解释并传给系统。
它为⽤户提供了⼀个向Linux发送请求以便运⾏程序的接⼝系统级程序,⽤户可以⽤Shell来启动、挂起、停⽌甚3⾄是编写⼀些程序。
Shell本⾝是⼀个⽤C语⾔编写的程序,它是⽤户使⽤Linux的桥梁。
Shell既是⼀种命令语⾔,⼜是⼀种(就是你所说的shell脚本)。
作为命令语⾔,它互动式地解释和执⾏⽤户输⼊的命令;作为程序设计语⾔,它定义了各种和参数,并提供了许多在⾼阶语⾔中才具有的控制结构,包括循环和分⽀。
它虽然不是 Linux系统的⼀部分,但它调⽤了系统内核的⼤部分功能来执⾏程序、创建⽂档并以并⾏的⽅式协调各个程序的运⾏。
交互式shell和⾮交互式shell 交互式模式就是shell等待你的输⼊,并且执⾏你提交的命令。
这种模式被称作交互式是因为shell与⽤户进⾏交互。
这种模式也是⼤多数⽤户⾮常熟悉的:登录、执⾏⼀些命令、签退。
当你签退后,shell也终⽌了。
shell也可以运⾏在另外⼀种模式:⾮交互式模式。
在这种模式下,shell不与你进⾏交互,⽽是读取存放在⽂件中的命令,并且执⾏它们。
当它读到⽂件的结尾,shell也就终⽌了。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
【例子:001】判断输入为数字,字符或其他1.#!/bin/bash2.read -p "Enter a number or string here:" input3.case $input in4. [0-9]) echo -e "Good job, Your input is a numberic! \n" ;;5.[a-zA-Z]) echo -e "Good job, Your input is a character! \n" ;;6. *) echo -e "Your input is wrong, input again! \n" ;;7.esac【例子:002】求平均数1.#!/bin/bash2.# Calculate the average of a series of numbers.3.SCORE="0"4.AVERAGE="0"5.SUM="0"6.NUM="0"7.while true; do8. echo -n "Enter your score [0-100%] ('q' for quit): "; read SCORE;9. if (("$SCORE" < "0")) || (("$SCORE" > "100")); then10. echo "Be serious. Common, try again: "11. elif [ "$SCORE" == "q" ]; then12. echo "Average rating: $AVERAGE%."13. break14. else15. SUM=$[$SUM + $SCORE]16. NUM=$[$NUM + 1]17. AVERAGE=$[$SUM / $NUM]18. fi19.done20.echo "Exiting."【例子:003】自减输出1.[scriptname: doit.sh]2.while (( $# > 0 ))3.do4. echo $*5. shift6.done7./> ./doit.sh a b c d e8. a b c d e9. b c d e10.c d e11.d e12.e【例子:004】在文件中添加前缀1.# 人名列表2.# cat namelist3.Jame4.Bob5.Tom6.Jerry7.Sherry8.Alice9.John10.# 脚本程序11.# cat namelist.sh12.#!/bin/bash13.for name in $(cat namelist)14.do15. echo "name= " $name16.done17.echo "The name is out of namelist file"18.# 输出结果19.# ./namelist.sh= Jame= Bob= Tom= Jerry= Sherry= Alice= John【例子:005】批量测试文件是否存在1.[root@host ~]# cat testfile.sh2.#!/bin/bash3.for file in test*.sh4.do5. if [ -f $file ];then6. echo "$file existed."7. fi8.done9.[root@host ~]# ./testfile.sh10.test.sh existed.11.test1.sh existed.12.test2.sh existed.13.test3.sh existed.14.test4.sh existed.15.test5.sh existed.16.test78.sh existed.17.test_dev_null.sh existed.18.testfile.sh existed.【例子:005】用指定大小文件填充硬盘1.[root@host ~]# df -ih /tmp2.Filesystem Inodes IUsed IFree IUse% Mounted on3./dev/mapper/vg00-lvol54. 1000K 3.8K 997K 1% /tmp5.[root@host ~]# cat cover_disk.sh6.#!/bin/env bash7.counter=08.max=38009.remainder=010.while true11.do12. ((counter=counter+1))13. if [ ${#counter} -gt $max ];then14. break15. fi16. ((remainder=counter%1000))17. if [ $remainder -eq 0 ];then18. echo -e "counter=$counter\tdate=" $(date)19. fi20. mkdir -p /tmp/temp21. cat < testfile > "/tmp/temp/myfile.$counter"22. if [ $? -ne 0 ];then23. echo "Failed to write file to Disk."24. exit 125. fi26.done27.echo "Done!"28.[root@host ~]# ./cover_disk.sh29.counter=1000 date= Wed Sep 10 09:20:39 HKT 201430.counter=2000 date= Wed Sep 10 09:20:48 HKT 201431.counter=3000 date= Wed Sep 10 09:20:56 HKT 201432.cat: write error: No space left on device33.Failed to write file to Disk.34.dd if=/dev/zero of=testfile bs=1M count=1【例子:006】通过遍历的方法读取配置文件1.[root@host ~]# cat hosts.allow2.127.0.0.13.127.0.0.24.127.0.0.35.127.0.0.46.127.0.0.57.127.0.0.68.127.0.0.79.127.0.0.810.127.0.0.911.[root@host ~]# cat readlines.sh12.#!/bin/env bash13.i=014.while read LINE;do15. hosts_allow[$i]=$LINE16. ((i++))17.done < hosts.allow18.for ((i=1;i<=${#hosts_allow[@]};i++)); do19. echo ${hosts_allow[$i]}20.done21.echo "Done"22.[root@host ~]# ./readlines.sh23.127.0.0.224.127.0.0.325.127.0.0.426.127.0.0.527.127.0.0.628.127.0.0.729.127.0.0.830.127.0.0.931.Done【例子:007】简单正则表达式应用1.[root@host ~]# cat regex.sh2.#!/bin/env sh3.#Filename: regex.sh4.regex="[A-Za-z0-9]{6}"5.if [[ $1 =~ $regex ]]6.then7. num=$18. echo $num9.else10. echo "Invalid entry"11. exit 112.fi13.[root@host ~]# ./regex.sh 123abc14.123abc15.#!/bin/env bash16.#Filename: validint.sh17.validint(){18. ret=`echo $1 | awk '{start = match($1,/^-?[0-9]+$/);if (start == 0) print "1";else print "0"}'`19. return $ret20.}21.validint $122.if [ $? -ne 0 ]; then23. echo "Wrong Entry"24. exit 125.else26. echo "OK! Input number is:" $127.fi【例子:008】简单的按日期备份文件1.#!/bin/bash2.NOW=$(date +"%m-%d-%Y") # 当前日期3.FILE="backup.$NOW.tar.gz" # 备份文件4.echo "Backing up data to /tmp/backup.$NOW.tar.gz file, please wait..." #打印信息5.tar xcvf /tmp/backup.$NOW.tar.gz /home/ /etc/ /var # 同时备份多个文件到指定的tar压缩文件中6.echo "Done..."【例子:009】交互式环境select的使用1.#!/bin/bash2.echo "What is your favorite OS?"3.select OS in "Windows" "Linux/Unix" "Mac OS" "Other"4.do5. break6.done7.echo "You have selected $OS"8.root@localhost:~/training# ./select.sh9.What is your favorite OS?10.1) Windows11.2) Linux/Unix12.3) Mac OS13.4) Other14.#? 115.You have selected Windows【例子:010】批量修改文件名的脚本1.#!/bin/bash2.# we have less than 3 arguments. Print the help text:3.if [ $# -lt 3 ]; then4. cat <<-EOF5. ren -- renames a number of files using sed regular expressions6. USAGE: ren.sh 'regexp' 'replacement' files7. EXAMPLE: rename all *.HTM files in *.html:8. ren 'HTM$' 'html' *.HTM9. EOF10. exit 011.fi12.OLD="$1"13.NEW="$2"14.# The shift command removes one argument from the list of15.# command line arguments.16.shift17.shift18.# $* contains now all the files:19.for file in $*20.do21.if [ -f "$file" ]; then22. newfile=`echo "$file" | sed "s/${OLD}/${NEW}/g"`23. if [ -f "$newfile" ]; then24. echo "ERROR: $newfile exists already"25. else26. echo "renaming $file to $newfile "27. mv "$file" "$newfile"28. fi29.fi30.done31.root@localhost:~/training# ./ren.sh "HTML$" "html" file*.HTML32.renaming file10.HTML to file10.html33.renaming file1.HTML to file1.html34.renaming file2.HTML to file2.html35.renaming file3.HTML to file3.html36.renaming file4.HTML to file4.html37.renaming file5.HTML to file5.html38.renaming file6.HTML to file6.html39.renaming file7.HTML to file7.html40.renaming file8.HTML to file8.html41.renaming file9.HTML to file9.html【例子:011】break语句在脚本中的应用示例1.#!/bin/bash2.for VAR1 in 1 2 33.do4. for VAR2 in 0 55. do6. if [ $VAR1 -eq 2 -a $VAR2 -eq 0 ]7. then8. break 2 # 退出第二重循环,亦即退出整个循环9. else10. echo "第一个变量:$VAR1 第二个变量:$VAR2"11. fi12. done13.done14.root@localhost:~/training# ./test.sh15.第一个变量:1 第二个变量:016.第一个变量:1 第二个变量:5【例子:012】/dev/tty在读取人工输入中的特殊作用1.#!/bin/bash2.# 用来验证两次输入的密码是否一致3.printf "Enter your passwd: " # 提示输入4.stty -echo # 关闭自动打印输入字符的功能5.read pwd1 < /dev/tty # 读取密码6.printf "\nEnter again: " # 再次提示输入7.read pwd2 < /dev/tty # 再读取一次以确认8.stty echo # 打开自动打印输入字符的功能9.if [[ "$pwd1" == "$pwd2" ]]; then # 对两次输入的密码进行判断10. echo -e "\nPASSWORD: the same"11.else12. echo -e "\nPASSWORD: not same"13.fi14.root@localhost:~/training# ./test.sh15.Enter your passwd:16.Enter again:17.PASSWORD: the same【例子:013】/dev/null在脚本中的简单示例1.#!/bin/bash2.if grep /bin/bash $0 > /dev/null 2>&1 # 只关心命令的退出状态而不管其输出3.then # 对退出状态进行判断4. echo -e "/bin/bash in $0\n"5.else6. echo -e "/bin/bash not in $0\n"7.fi8.脚本输出:9.root@localhost:~/training# ./test.sh10./bin/bash in ./test.sh【例子:014】构建自己的bin目录存放执行脚本,然后随便执行的简单示例1.$ cd # 进入家目录2.$ mkdir bin # 创建$HOME目录下自己的bin目录3.$ mv test.sh bin # 将我们自己的脚本放到创建的bin目录下4.$ PATH=$PATH:$HOME/bin # 将个人的bin目录放到PATH中5.$ test.sh # 现在就可以直接执行自己的脚本了【例子:015】将长句子中单词长度为5及以上的单词打印出来1.#!/bin/bash2.# filename: test.sh3.sentence="When you're attracted to someone it just means that your subconscious is attracted to their subconscious, subconsciously.4.So what we think of as fate, is just two neuroses knowing they're a perfect match."5.for word in ${sentence}6.do7. new=`echo $word | tr -cd '[a-zA-Z]'` # 去除句子中的,或者'8. len=${#new} # 求长度9. if [ "$len" -ge 5 ] # 再判断10. then11. echo $new12. fi13.done14.root@localhost:~# ./test.sh15.youre16.attracted17.someone18.means19.subconscious20.attracted21.their22.subconscious23.subconsciously24.think25.neuroses26.knowing27.theyre28.perfect29.match【例子:016】根据输入的数据(年4位,月2位),来判断上个月天数1.#!/bin/bash2.get_last_day()3.{4. year=`expr substr $1 1 4`5. month=`expr substr $1 5 2`6. curr_month=`echo $month | tr -d '0'` # 去掉里面的0,方便后面计算7. echo "curr_month=$curr_month"8. last_month=`expr $curr_month - 1`9. case $last_month in10. 01|03|05|07|08|10|12|0)11. echo "上个月天数-->" 31 ;;12. 02)13. if [ `expr $year % 400` = 0 ] ; then14. echo "上个月天数-->" 2915. elif [ `expr $year % 4` = 0 ] && [ `expr $year % 100` != 0 ] ; then16. echo "上个月天数-->" 2917. else18. echo "上个月天数-->" 2819. fi ;;20. *)21. echo "上个月天数-->" 3022. esac23.}24.if [ $# -ne 1 ]; then25. echo "Usage: $0 201608"26.else27. get_last_day $128.fi29.root@localhost:~/training# ./test.sh 20160130.上个月天数--> 31【例子:017】统计文件中每个单词出现的频率1.#!/bin/sh2.# 从标准输入读取文件流,再输出出现频率的前n,默认:25个单词的列表3.# 附上出现频率的计数,按照这个计数由大到小排列4.# 输出到标准输出5.# 语法: wf [n]6.tr -cs A-Za-z\' '\n' |7. tr A-Z a-z |8. sort |9. uniq -c |10. sort -k1,1nr -k2 |11. sed ${1:-25}q12.root@localhost:~/training# wf 10 < /etc/hosts | pr -c4 -t -w8013. 6 ip 1 1 archive 1 capable14. 3 ff 1 allnodes 1 are 1 cn15. 2 localhost 1 allrouters【例子:018】使用while和break等待用户登录1.#!/bin/bash2.# 等待特定用户登录,每30秒确认一次3.# filename: wait_for_user_login.sh4.read -p "Ener username:-> " user5.while true6.do7. if who | grep "$user" > /dev/null8. then9. echo "The $user now logged in."10. break11. else12. sleep 3013. fi14.done15.root@localhost:~/shell# ./wait_for_user_login.sh16.Ener username:-> guest17.The guest now logged in.【例子:019】结合while,case,break,shift做简单的选项处理1.#!/bin/bash2.# 将标志变量设置为空值3.file= verbose= quiet= long=4.while [ $# -gt 0 ] # 执行循环直到没有参数为止5.do6. case $1 in # 检查第一个参数7. -f) file=$28. shift ;; # 移位-f,使得结尾shift得到$2的值9. -v) verbose=true10. quiet= ;;11. -q) quiet=true12. verbose= ;;13. -l) long=true ;;14. --) shift15. break ;;16. -*) echo "$0: $1: unrecongnized option >&2" ;;17. *) break ;;18. esac19.done20.~【例子:020】read读取多个变量处理,及文本遍历的两种常用方式1.#!/bin/bash2.while IFS=: read user pwd pid gid fullname homedir shell # IFS作为列之间的分隔符号,read读取多个变量3.do4. printf "The user=%s homedir=%s\n" "$user" "$homedir" # 对文本中的行进行处理5.done < /etc/passwd # 读取文件6.# 第二种方式7.#!/bin/bash8.cat /etc/passwd |9. while IFS=: read user pwd pid gid fullname homedir shell10.do11. printf "The user=%s homedir=%s\n" "$user" "$homedir"12.done【例子:021】复制目录树的两个简单脚本1.#!/bin/bash2.# 方式一3.find /root/shell -type d -print | # 寻找所有目录4. sed 's;/root/shell/;/tmp/shell/;' | # 更改名称,使用;作为定界符5. sed 's/^/mkdir -p /' | # 插入mkdir -p 命令6. sh -x # 以Shell的跟踪模式执行7.# 方式二8.find /root/shell -type d -print | # 寻找所有目录9. sed 's;/root/shell/;/tmp/shell/;' | # 更改名称,使用;作为定界符10. while read newdir # 读取新的目录名11. do12. mkdir -p $newdir13. done14.~【例子:022】发邮件给系统前10名磁盘用户,要求清理磁盘空间1.#!/bin/bash2.cd /home # 移动到目录的顶端3.du -s * | # 产生原始磁盘用量4. sort -nr | # 以数字排序,最高的在第一位5. sed 10q | # 在前10行之后就停止6. while read amount name # 将读取的数据分别作为amount, name变量7. do8. mail -s "disk usage warning" $name << EOF9.Gretings. You are one of the top 10 consumers of disk space10.on the system. Your home directory users $amount disk blocks.11.Please clean up unneeded files, as soon as possible.12.Thanks,13.Your friendly neighborhood system administrator.14.EOF15. done【例子:023】将密码文件转换为Shell邮寄列表1.#!/bin/bash2.# passwd-to-mailing-list3.#4.# 产生使用特定shell的所有用户邮寄列表5.#6.# 语法: passwd-to-mailing-list < /etc/passwd7.# 删除临时性文件8.rm -rf /tmp/*.mailing-list9.# 从标准输入中读取10.while IFS=: read user passwd uid gid name home Shell11.do12. Shell=${Shell:-/bin/sh} # 如为空shell,指/bin/sh13. file="/tmp/$(echo $Shell | sed -e 's;^/;;' -e 's;/;-;g').mailing-list"14. echo $user, >> $file15.done16.root@localhost:~# vim passwd-to-mailing-list17.root@localhost:~# passwd-to-mailing-list < /etc/passwd18.root@localhost:~# cat /tmp/bin-bash.mailing-list19.root,20.test,er,22.root@localhost:~# cat /tmp/bin-sh.mailing-list23.libuuid,24.jerry,【例子:024】变更目录时更新PS11.#!/bin/bash2.cd()3.{4. command cd "$@" # 实际改变目录5. x=$(pwd) # 取得当前目录的名称,传递给变量6. PS1="${x##*/}\$ " # 截断前面的组成部分,指定给PS17.}8.root$ # 最后输出,类似于这种,看不到目录的完整路径【例子:025】根据XML文件中的license时间来判断是否过期1.2.3.中国,福建,福州市,鼓楼区4. 1231235. hdsas_base_3.0.0.2_16Q2_RC26. _RC257971fe611f07. f04c3d1eb4bf61138. 2016-08-02 16:46:399. 30 days10.11.获得2016-08-02 16:46:39时间加上30 days12.期限,得到时间减去系统当前时间,小于7天,显示license即将在几天后过期。