@yanglt7
2018-11-01T15:09:41.000000Z
字数 2618
阅读 836
Shell
| cmd | description |
|---|---|
| break n | 如果省略 n,则表示跳出整个循环,n 表示跳出循环的层数 |
| continue n | 如果省略 n,则表示跳过本次循环,忽略本次循环的剩余代码,进入循环的下一次循环。n 表示退到第 n 层继续循环 |
| exit n | 退出当前 Shell 程序, n 为上一次程序执行的状态返回值。n 也可以省略,在下一个 Shell 里可通过 “$?” 接收 exit 的 n 值 |
| return n | 用于在函数里作为函数的返回值,以判断函数执行是否正确。在下一个 shell 里可通过 “$?” 接收 exit n 的 n值 |
例 11-1
#!/bin/bashif [ $# -ne 1 ];thenecho "usage:$0 {break|continue|exit|return}"exit 1fitest(){for ((i=0; i<=5; i++))doif [ $i -eq 3 ];then$*;fiecho $idoneecho "I am func."}test $*func_ret=$?if [ `echo $*|grep return|wc -l` -eq 1 ];thenecho "return's exit status:$func_ret"fiecho "ok"
[root@web001 scripts]# sh 251.shusage:251.sh {break|continue|exit|return}
[root@web001 scripts]# sh 251.sh break012I am func.ok
[root@web001 scripts]# sh 251.sh continue01245I am func.ok
[root@web001 scripts]# sh 251.sh return012return's exit status:0ok
[root@web001 scripts]# sh 251.sh exit012
例 11-2 开发 Shell 脚本实现为服务器临时配置多个 IP,并且可以随时撤销配置的所有 IP。IP 的地址范围为 10.0.2.1~10.0.2.16,其中 10.0.2.10 不能配置。
给网卡配置额外的 IP。
方法 1:使用 ifconfig 配置别名 IP 的方法:
ifconfig ens33:0 10.0.2.10/24 up #<== 添加 IPifconfig ens3:0 10.0.2.10/24 down #<== 删除 IP
方法 2:使用 IP 配置辅助 IP 的方法:
ip addr add 10.0.2.11/24 dev ens33 label ens33:0ip addr del 10.0.2.11/24 dev ens33 label ens33:0
#!/bin/bash[ -f /etc/init.d/functions ] && . /etc/init.d/functionsRETVAL=0op(){if [ "$1" == "del" ];thenlist=`echo {16..1}`elselist=`echo {1..16}`fifor ip in listdoif [ $ip -eq 10 ];thencontinuefiip addr $1 10.0.2.$ip/24 dev ens33 label ens33:$ip &>/dev/nullRETVAL=$?if [ $RETVAL -eq 0 ];thenaction "$1 $ip" /bin/trueelseaction "$1 $ip" /bin/falsefidonereturn $RETVAL}case "$1" instart)op addRETVAL=$?;;stop)op delRETVAL=$?;;restart)op delsleep2op addRETVAL=$?;;*)printf "USAGE:$0 {start|stop|restart}\n"esacexit $RETVAL
例 11-3 分析 Apache 访问日志,把日志中每行的访问字节数所对应的字段数字相加,计算出总的访问量。
方法 1:while 循环(采用 bash exec 内置命令和 expr 判断整数)
#!/bin/bashsum=0exec <$1while read linedosize=`echo $line|awk '{print $10}'`expr $size + 1 &>/dev/nullif [ $? -ne 0 ];thencontinuefi((sum=sum+size))doneecho "${1}:total:${sum}bytes =`echo $((${sum}/1024))`KB"
方法2:while 循环(采用 bash exec 内置命令 + 变量字串替换特殊方方来判断整数)
exec <$1sum=0while read linedonum=`echo $line|awk '{print $10}'`[ -n "$num" -a "$num" = "${num//[^0-9]/}" ] || continue((sum=sum+num))doneecho "${1}:${num} bytes =`echo $((${num}/1024))`KB"
方法 3:
exec <access_www.logsum=0while read linedo[ -z "`echo $line|awk '{print $10}'|sed 's#[0-9]##g'`" ] || continue((sum=sum+`echo $line|awk '{print $10}'`))doneecho $sum
例 11-4 已知下面的字符串是通过将 RANDOM 随机数采用 md5sum 加密后任意取出连续 10 位的结果,请破解这些字符串对应的 md5sum 前的数字?
4fe8bf20ed
#!/bin/bashfor n in {0..32767}doecho "`echo $n|md5sum` $n" >>/tmp/zhiwen.logdone
md5char="4fe8bf20ed"while read linedoif [ `echo $line|grep "md5char"|wc -l` -eq 1 ];thenecho $linebreakfidone </tmp/zhiwen.log