当前位置:网站首页>Shell -- circular statements (for, while, until)
Shell -- circular statements (for, while, until)
2022-07-27 06:37:00 【m0_ sixty-nine million five hundred and ten thousand two hundre】
List of articles
One 、for loop
In practice , There are often situations where a task needs to be performed many times , And each time it is executed, it is only processed
Different objects , The other commands are the same . for example , Create a system account according to the name list in the address book , Check the survival status of each host according to the server list
When repeating tasks in the face of various lists , Easy to use if Statement has been difficult to meet the requirements , Writing all the code in sequence is extremely cumbersome 、 The difficulties
1、for Loop structure
- List loop
- Loop without list
- class c Style for loop
Format
for Variable name in {}
do
echo $i
done
give an example
for i in {1..5}
do
echo $i
done
# perform
1
2
3
4
5
perhaps
for i in `seq 5` # You can introduce variables
do
echo $i
done
# perform
1
2
3
4
5
Take a chestnut : use for loop , Output 10 An odd number within
for i in $(seq 1 2 10)
do
echo $i
done
# perform
1
3
5
7
9
#for i in $(seq 1 2 10)
1-10 The odd number , middle 2 Step length
2、 class c Style for loop
Format
for ((expr1;expr2;expr3))
do
command
done
expr1: Define variables and assign initial values
expr2: Decide whether to cycle or not
expr3: Decide how the loop variable changes , Decide when the loop will exit
for example
for ((i=1;i<=5;i++))
do
echo $i
done
On the first output 1, Then start entering the loop , Each cycle will add 1, To 5 end
Execution results :
1
2
3
4
5
notes :i++ :i=1+1 Let's start with the assignment i=1 after Again +1
++i : 1+1=i Operation before assignment 1+1 after Again =1
Take a chestnut
1. Output 1-10 Odd sum of
sum=1
for ((i=1;1<=10;1+=2))
do
let sum=$sum+$i
done
echo "$sum"
# perform
25
2. Random roll call
touch name # First create a list file
vim name # Write name
#!/bin/bash
w=$[RANDOM%5+1] # Define random number variables , The random number is 1-5 Within the scope of (RANDOM% Random numbers are from 0 At first, therefore +1)
for i in $(grep -w $w ~/for/name)
do
echo "$i"
done
# Then execute it
3. Batch add users
#!/bin/bash
ULIST=$(cat /root/users.txt)
for UNAME in $ULIST
do
useradd $UNAME
echo "123456" | passwd --stdin $UNAME &>/dev/null
done
4. Volume delete user's script
vim udelfor.sh
#!/bin/bash
ULIST=$(cat /root/users.txt)
for UNAME in $ULIST
do
userdel -r $UNAME &>/dev/null
done
Two 、while sentence
while Loops are generally used for conditional judgment loops , If the judgment condition is true , Then enter the cycle , When the condition is false, jump out of the loop
Format
while expression
do
command
done
for example
i=1
n=0
while [ $i - le 5 ]
do
echo $i
let i++ #/ Note that if this doesn't change $i Value , It's going to be a dead cycle
let n++
done
echo " The final value :$i; loop :$n Time "
Take a chestnut
- Output 1-100 Can't be 3 Divisible numbers
#!/bin/bash
i=1
while [ $i -le 100 ] #i The value is less than 100
do
if [[ $i%3 -ne 0 ]] # And i except 3 The value of the remainder is equal to 0
then echo "$i" # Can be output and displayed
fi
let i++
done
1、while Dead cycle
Format
while [ 1 -eq 1 ] // Write an expression that is always true ,1 be equal to 1 This condition is always true , So this script will continue to loop
do
command
done
Take a chestnut
- Guess the number game ( Guess wrong and keep guessing )
#!/bin/bash
one=$[RANDOM%10+1]
i=0
while true
do
read -p " Please enter 1-10 A number in :" o
let i++
if [ $i -gt 3 ];then
if [ $o -eq $one ];then
echo " The game failed , Next time try "
break
fi
else
if [ $o -eq $one ];then
echo " congratulations , You guessed right in three times "
exit
fi
fi
if [ $o -gt $one ];then
echo " Guess the , Once again "
elif [ $o -lt $one ];then
echo " Guess a little , Once again "
fi
done
echo " How many times do you enter $i"
3、 ... and 、until loop
Follow while contrary , If the condition is false, enter the loop , If the condition is true, exit the loop
Grammatical structure
until expression
do
command
done
- Calculation 1-50 And 1275 There are two ways to write the first
#!/bin/bash
i=0;s=0
until [ $i -eq 51 ]
do
let s+=i #s+=i, Equivalent to s=s+i, Use plus assignment
let i++
done
echo $s
# The second kind
#!/bin/bash
i=1
sum=0
until [ $i -eq 51 ] # Note here that if it is 50 If the condition is true, the loop ends and it calculates 1-49 And ,until [ $i -gt 50 ] It's OK
do
sum=$[$i+$sum]
let i++
done
echo "$sum"
1、 Dead cycle structure
until false
do
command
done
until [ 1 -ne 1 ]
do
command
done
Take a chestnut
- Sign in zhangsan user Use root Send a message zhangsan
#!/bin/bash
username=$1
# Determine the format of information
if [ $# -lt 1 ];then
echo "Usage:`basename $0` <username> [<message>]"
exit 1
fi
# Judge whether the user exists
if grep "^$username:" /etc/passwd >/dev/null ;then :
else
echo " The user doesn't exist "
exit 1
fi
# Is the user online , If not online, every 5 Contact once a second
until who|grep "$username" >/dev/null
do
echo " The user doesn't exist "
sleep 5
done
mes=$*
echo $mes | write $username
notes : Switch the user during the test
Four 、 Loop control statement
for Loops are generally executed together with conditional judgment statements and process control statements , Then you need to skip the loop and abort the loop , The commands to control the loop are as follows 3 individual
1、continue
continue It means to continue , but The following code in the loop body will not be executed 了 , Start Restart the next cycle
for example : Print 1-5 The number of ,3 No printing
#!/bin/bash
for ((i=1;i<=5;i++))
do
if [ $i -eq 3 ];then
continue
else
echo $i
fi
done
The result is 1245,3 No output , Because jump out of the back echo Statement executes the next loop
2、break
break Indicates interruption , Stop this cycle immediately , Execute the extracorporeal code
for example :1-10 The number of ,7 The back ones don't print
#!/bin/bash
for ((i=1;i<=10;i++))
do
if [ $i -eq 8 ];then
break
else
echo $i
fi
done
3、exit
exit Express Jump out of the program , It can be followed by a status return code, such as exit 1 wait
for example :1-5 The number of , To 3 Then exit the loop with a return code exit 100
for i in {1..5}
do
if [ $i -eq 3 ];then
exit 100
else
echo $i
fi
done
echo hi
Jump out of the program directly, so the final... Will not be executed echo hi, And the return code is 100 adopt $? see
边栏推荐
猜你喜欢
随机推荐
PLL of IP core
Shell script if nested for loop script
KVM命令集管理虚拟机
Programming learning records - Lesson 9 [operators]
多线程的相关知识
ArcGIS for JS API (2) get the ID set of element services
哈希表简介
Open source WebGIS related knowledge
5g network identity - detailed explanation of 5g Guti
Random points in non overlapping rectangle (force deduction daily question)
Programming learning records - Lesson 4 [branch and loop statements]
Multi coordinate transformation
Markdown文档常用字体及颜色设置
Interface test process and interview questions
DNS故障分析优化
Install Wireshark correctly
Briefly remember the top ten orders
Launch file of ROS operation management
Shell script loop
Cesium tutorial (1) interface introduction -3dfiles loading - change mouse operation settings









