shell中循环的三种情况
2020-04-18 本文已影响0人
南南宫问天
exit 结束循环
continue 继续执行
break 跳出循环体 执行循环外的命令
[root@db scripts]# cat exit.sh
#!/bin/bash
for i in `seq 10`
do
useradd czq$i
if [ $? -eq 0 ];then
echo "create $i Success"
else
exit
fi
done
echo done.................
[root@db scripts]# sh exit.sh
create 1 Success
create 2 Success
create 3 Success
create 4 Success
useradd:用户“czq5”已存在 ##exit 当判断到用户已经存在时,整个循环和脚本都退出
[root@db scripts]# cat continue.sh
#!/bin/bash
for i in `seq 10`
do
useradd czq$i
if [ $? -eq 0 ];then
echo "create $i Success"
else
continue
fi
done
echo done.................
[root@db scripts]# sh continue.sh
create 1 Success
create 2 Success
create 3 Success
create 4 Success
useradd:用户“czq5”已存在 ##contineue 跳过此次循环,继续执行循环
create 6 Success
create 7 Success
create 8 Success
create 9 Success
create 10 Success
done.................
[root@db scripts]# cat break.sh
#!/bin/bash
for i in `seq 10`
do
useradd czq$i
if [ $? -eq 0 ];then
echo "create $i Success"
else
break
fi
done
echo done.................
[root@db scripts]# sh break.sh
create 1 Success
create 2 Success
create 3 Success
create 4 Success
useradd:用户“czq5”已存在 ##break 当判断到用户已经存在时,跳出循环体,执行外面的命令
done.................