循环控制:
continue: 提前结束本次循环而开始评估下一轮;
break [n]: 跳出当前循环 ,如果有多层默认不指定则跳出一层(n 可以指定跳出几层循环,n大于或等于1,如当需要跳出多个for循环)
练习:
1、求100以内所整数之和;
#!/bin/bash # declare -i sum=0 declare -i i=1 # while true;do if [ $i -gt 100 ];then break \\ 如果条件满足则跳出while循环 else let sum=$sum+$i let i++ fi done echo $sum
2、求100以内所有偶数之和;
#!/bin/bash # declare -i sum=0 declare -i i=1 # while [ $i -le 100 ];do if [ $[$i%2] -eq 1 ];then let i++ continue \\ 如果条件满足则结束本次循环,后面的语句将不再进行。 fi let sum+=$i let i++ done echo $sum
3、提示用户输入用户名,显示用户的ID号;直到用户输入quit退出;
#!/bin/bash # while true;do read -p "please enter user: " userName if [ "$userName" == quit ];then exit 7 fi if [ -z "$userName" ] || ! id $userName >& /dev/null ;then echo "you enter user not exist or null." continue fi echo "$userName ID Number Is:`id -u $userName`" done
4、
(a)、提示用户输入一个磁盘设备的设备文件,如果设备文件不存在,就提示用户重新输入,直到用户输入正确为止;
(b)、用户可以输入quit退出;
#!/bin/bash # while true;do read -p "please enter block device: " Device if [[ "$Device" == quit ]];then exit 8 fi [ -b "$Device" ] && break || echo "error enter !!!" done echo "you enter block device is: $Device."
扩展前一题
当用户给出正确的块设备后:
1、显示用户输入块设备,并提示用户,后续的操作会损坏设备上的所有文件,让用户选择是否继续
2、如果用户输入y,则继续后面的操作;
3、如果用户输入n,则显示用户选择了中止,并退出脚本;
4、输入任何其它字符,则让用户重新选择;
5、如果用户选择了y, 则抹除指定块设备上的所有分区;
#!/bin/bash # while true;do read -p "please enter block device: " Device if [[ "$Device" == quit ]];then exit 8 fi [ -b "$Device" ] && break || echo "error enter !!!" done echo "you enter block device is: $Device." while true;do read -p "enter Y|y contiue or N|n exit." option option=`echo $option | tr 'A-Z' 'a-z'` if [[ "$option" == y ]];then break elif [[ "$option" == n ]];then exit 7 else echo "Wrong input..." fi done dd if=/dev/zero of=$Device bs=512 count=1
练习:写一个脚本
前提:配置好yum源
1、如果本机没有一个可用的yum源,则提示用户,并退出脚本(4);如果此脚本非以root用户执行,则显示仅有root才有权限安装程序包,而后退出(3);
2、提示用户输入一个程序包名称,而后使用yum自动安装之;尽可能不输出yum命令执行中的信息;
如果安装成功,则绿色显示,否则,红色显示失败;
3、如果用户输入的程序包不存在,则显示错误后让用户继续输入;
4、如果用户输入quit,则正常退出(0);
5、正常退出前,显示本地共安装的程序包的个数;
转载于:https://blog.51cto.com/zkxfoo/1753032