shell study-13day--out of the loop (break, continue)

1. Jump out of the loop ( break and continue )

( 1) Jump out of the loop

In the process of using a loop statement to loop, sometimes it is necessary to force a loop out of the loop when the loop end condition is not reached. Shell provides two commands to achieve this function: break and continue.

Break: Jump out of the entire loop

Break overview: Jump out of the current entire loop or end the current loop . In loop statements such as for, while, it is used to jump out of the loop body currently in, and execute the statement after the loop body. If nothing is added later, it means that it is equivalent to jumping out of the current loop. For break 1, you can also add a number after it, assuming break3 means jumping out of the third loop.


Continue: skip this cycle and proceed to the next cycle

continue Overview: Ignore the remaining code in this loop and proceed directly to the next loop; in loop statements such as for, while, it is used to jump out of the loop body currently in, and execute the statement after the loop body. If the number added after the loop is 1, It means to ignore this conditional loop, if it is 2, ignore the 2 conditional loops.

( 2) Example 1

[root@test shell]# cat case.sh 
#!/bin/bash
for ((i=0;i<=4;i++)) ; do
  echo $i
  case $i in
  1)
    echo "This is one"
    ;;
  2)
    continue  #跳出本次循环 
    echo "This is two"
    ;;
  3)
    break  #跳出整个循环
    echo "This is three"
    ;;
  4)
    echo "This is four"
    ;;
  esac
done
[root@test shell]# sh case.sh 
0
1
This is one
2
3
[root@test shell]#

( 3) Use interactive methods to add users in batches

[root@test shell]# vi useradd.sh 
#!/bin/bash 
echo "*********************" 
read -p "Please enter what you want to create Username: "name 
read -p" Please enter the number of users to be created: "num 
read -p" Please enter the password for the user to be created: "pas 
echo "**************** *****" 
for ((i=1;i<=$num;i=i+1)) 
do 
useradd $name$i &> /dev/null 
echo "$pas" | passwd --stdin $name $i &> /dev/null 
done 
echo "The user is created, the result is..." 
tail -$num /etc/passwd 
[root@test shell]# sh useradd.sh  
********** *********** 
Please enter the user name to be created: test 
Please enter the number of users to be created: 1 
Please enter the password of the user to be created: 123456 
************* ********The 
user creation is complete, the result is... 
test1:x:504:504::/home/test1:/bin/bash
[root@test shell]#

Personal public number:

image.png

Guess you like

Origin blog.51cto.com/13440764/2575388