目录
学习笔记:CentOS7学习之二十三: 跳出循环-shift参数左移-函数的使用
本文用于记录学习体会、心得,兼做笔记使用,方便以后复习总结。内容基本完全参考学神教育教材,图片大多取材自学神教育资料,在此非常感谢MK老师和学神教育的优质教学。希望各位因学习需求而要进行转载时,能申明出处为学神教育,谢谢各位!
23.1 跳出循环
在我们使用循环语句进行循环的过程中,有时候需要在未达到循环结束条件时强制跳出循环,那么Shell给我们提供了两个命令来实现该功能:break和continue
23.1.1 break和continue
Break:跳出整个循环
Continue:跳过本次循环,进行下次循环
-
break概述:跳出当前整个循环或结束当前循环,在for、while等循环语句中,用于跳出当前所在的循环体,执行循环体之后的语句,后面如果什么也不加,表示跳出当前循环等价于break 1,也可以在后面加数字,假设break 3表示跳出第三层循环
-
continue概述:忽略本次循环剩余的代码,直接进行下一次循环;在for、while等循环语句中,用于跳出当前所在的循环体,执行循环体之后的语句,如果后面加的数字是1,表示忽略本次条件循环,如果是2的话,忽略下来2次条件的循环
例1:写一个shell菜单,当按数字键4时退出,否则一直循环显示
[root@centos-7-24 tmp]# vim break-continue.sh
#!/bin/bash
while true
do
echo "**************************"
echo "please select your choice:"
echo "1 copy"
echo "2 delete"
echo "3 backup"
echo "4 quit"
echo "**************************"
read op
case $op in
1|copy)
continue # 这里加了continue后,后面的echo语句就不会执行了
echo "your choice is copy"
;;
2|delete)
echo "your choice is delete"
;;
3|backup)
echo "your choice is backup"
;;
4|quit)
echo "EXIT.."
exit
;;
*)
echo "invalid selection, please try again"
esac
done
[root@centos-7-24 tmp]# bash break-continue.sh
**************************
please select your choice:
1 copy
2 delete
3 backup
4 quit
**************************
1
**************************
please select your choice:
1 copy
2 delete
3 backup
4 quit
**************************
2
your choice is delete
**************************
please select your choice:
1 copy
2 delete
3 backup
4 quit
**************************
3
your choice is backup
**************************
please select your choice:
1 copy
2 delete
3 backup
4 quit
**************************
4
EXIT..
例2:使用交互式方法批量添加用户
[root@centos-7-24 tmp]# vim adduser.sh
#/bin/bash
while true
do
read -p "please input prefix & password & num:" pre pass num
# 读取添加用户的前缀、通用密码、个数
printf "user information:
**********************
user prefix: $pre
user password: $pass
user num: $num
**********************
"
read -p "Are you sure?[y/n]" action # 读取用户互动选择
if [ $action == "y" ]; then
break
else
echo "please input your information again"
fi
done
for i in $(seq $num)
do
user=${pre}${i} # 定义用户名为前缀名加数字
id $user &> /dev/null
if [ $? -ne 0 ]; then # 判断用户是否已经存在,不存在则添加用户
useradd $user
echo "$pass"|passwd --stdin $user &> /dev/null
if [ $? -eq 0 ]; then
echo -e "