当前位置:网站首页>Circular statements and functions of shell scripts
Circular statements and functions of shell scripts
2022-07-19 02:45:00 【Nothing in the world is difficult 754】
List of articles
Loop statement
One ,for Loop statement structure
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 , Clear according to the server Check the survival status of each host , according to IP Address blacklist settings, access denied firewall policies, etc
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 . And in different scenarios, use different loop statements , It can solve similar problems well
for Structure of statement
- Read different values of variables , Used to execute the same set of commands one by one ,
- for There were , List loop , Loop without list , class C Style for loop
1.1 Format :
for Variable name in Value list
do
Command sequence
done
1.2 example :
List loop :
List loop :
1. example :
#!/bin/bash
a=3 // Defining variables
for i in `seq $a` //seq You can refer to variables
do
echo $i
done
[[email protected] opt]# sh 1.sh
1
2
3
2. example :
#!/bin/bash
for i in a b c //i There is actually no call here , So it's equivalent to in The following parameters will be cycled several times
do
echo 123
done
[[email protected] opt]# sh 1.sh
123
123
123
3. example :
#!/bin/bash
for i in a b c // Used here i Variable , So it displays normally i Value (a b c)
do
echo $i
done
[[email protected] opt]# sh 1.sh
a
b
c
4. example : Print 3 Time hello world, Although variables are defined i, But I didn't use it , It just controls the number of cycles
#!/bin/bash
for i in {
1..3} or `seq 5` or Corresponding numbers or letters (a b c,1 2 3 )
do
echo "hello world"
done
Summary :
for In circulation for i in {list} Usage mode
i Name the custom variable
in First of all, will in What follows , Define as a list Then loop through the values of the elements in the list , And assign it to the variable after each value i ( Custom variable name )
{list} list :① Define the number of cycles ② Every element , It will be taken out in turn at each cycle , Then copy it to the variable name
With do For division
command : Define each cycle , Instructions to output
done : end
Loop without list :
#!/bin/bash
for i
do
echo "hello"
done
[[email protected] opt]# sh 1.sh // No parameters were passed to the script, so there was no result
[[email protected] opt]# sh 1.sh a // hold a Assigned to i,i With the value, it starts to execute do..done 了
hello
The second kind :
#!/bin/bash
for i
do
echo "$i" // Change the constant display to , Variable display
done
[[email protected] opt]# sh 1.sh
[[email protected] opt]# sh 1.sh world
world
class C Style for loop :
Format :
for ((expr1;expr2;expr3))
do
command
done
expr1: Define variables and assign initial values i=1
expr2: Decide whether to cycle or not ( Define the range of values , The purpose is to define the number of cycles ) i<=3
expr3: Decide how the loop variable changes , Decide when the loop will exit ( Custom step size ) i++ or i=+2
1. example : Print 1-5
iteration
#!/bin/bash
for ((i=1;i<=3;i++))
do
echo "$i"
done
[[email protected] opt] sh 1.sh
1
2
3
2. example : Print 1-10 The odd number
#!/bin/bash
for ((i=1;i<=10;i+=2))
do
echo "$i"
done
2. example : Calculation 1-100 Odd and
#!/bin/bash
sum=0
for ((i=1;i<=100;i+=2))
do
let sum=$i+$sum
done
echo "$sum"
Two ,while Statement loop structure
- 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
- In short : Test a condition repeatedly , Repeat as long as the conditions are met
while Writing :
1. Grammatical structure
2. Dead cycle
2.1 Format :
while Conditional test operation
do
Command sequence
done
2.2 example :
1. example : Print 1-5
#!/bin/bash
i=1 // Defining variables i=1
while [ $i -le 5 ] // When i be equal to 5 Stop the cycle when
do
echo "$i" // Output per cycle i Value
let i++ // Each cycle +1
done // Cycle to greater than or equal 5 End cycle at
echo " Last i The value of is : $i" // Output last $i Value
[[email protected] while]# sh 1.sh
1
2
3
4
5
Last i The value of is : 6
2. example : Check the cycle several times based on the previous condition
#!/bin/bash
i=1
sum=0
while [ $i -le 5 ]
do
echo "$i"
let i+=2
let sum++
echo " Last i The value of is $i, Circulated $sum Time "
done
[[email protected] while]# sh 1.sh
1
Last i The value of is 3, Circulated 1 Time
3
Last i The value of is 5, Circulated 2 Time
5
Last i The value of is 7, Circulated 3 Time
2.2 Loop control statement
Loops are generally executed together with conditional judgment statements and process control statements , Then it will be necessary to skip the loop and stop the loop , There are three kinds of :
- exit: Support execution exited , The process executed by the current script , So you can end the script , You can define the return value to determine where the script went wrong ( Jump out of the program , It can be followed by the status return code , Jump out of the program directly, so the final... Will not be executed echo hi , And the return code is 100 adopt $? see )
- break: End the current script loop , It will not affect other loops written under the script ( interrupt , Stop this cycle immediately , Execute the extracorporeal code )
Print 1-10 The number of ,7 The back ones don't print
- continue: sign out ( At present ) This small cycle ( Nested inside ), Until you jump to the next cycle , If the conditions are true, the cycle will continue ( continue , But I won't execute the following code in the loop body , Start and restart the next cycle )
Print 1-5 The number of ,3 No printing , The results will be 1245,3 No output , Because jump out of the back echo Statement executes the next loop
while Dead cycle
i=1 ## Defining variables
while true [ $1 -eq 2 ] ## Used true Whether the judgment condition is true or not , Will execute in a loop
do
echo " Dead cycle "
# exit ## If you add cycle to exit Exit the current loop directly
done
2. Example guessing numbers , Guess wrong and keep guessing
#!/bin/bash
num=10
while true
do
read -p " Please enter a number :" zi
if [ $zi -eq $num ];then
echo " You guessed it "
break 1 ## It means you guessed right and quit the current cycle , Does not affect other nested loops
elif [ $zi -gt $num ];then
echo " You guessed big "
elif [ $zi -lt $num ];then
echo " You guess it's small "
fi
done
[[email protected] home]# vim while2.sh
#!/bin/bash
i=1 // Defining variables i=1
while [ $i -le 100 ] // Repeat the test $1 Less than or equal to 100, until $i be equal to 100
do // The list of commands
if [[ $i%3 -ne 0 ]] // Conditions for testing $i Remainder 3, Is not equal to 0
then // Conditions established
echo "$i" // Output $i Value
fi // End judgment
let i++ // Each cycle i+1
done // End of cycle
3、 ... and ,until Loop statement
- Follow while contrary , If the condition is false, enter the loop , If the condition is true, exit the loop
- Test a condition repeatedly , As long as the condition is not established, it will be executed repeatedly
3.1 Format :
until Conditional test operation
do
Command sequence
done
3.2 example :
[[email protected] home]# vim 50.sh
#!/bin/bash
i=1 // Defining variables i=1
sum=0
until [ $i -eq 51 ] //$i be equal to 51 Stop execution
do
sum=$[$i+$sum] // Definition sum be equal to $i + $sum
let i++ // Each cycle i+1
done
echo "$sum // Print the results $sum
[[email protected] home]# bash 50.sh
1275
until Dead cycle
Four ,shell function
- Write command sequences together in format
- It is convenient to reuse the command sequence
4.1 Format :
# Format 1 :
[ function ] Function name (){
Command sequence
[return x] // Use return or exit You can end the function explicitly
}
## Standard writing
#!/bin/bash
function dxj{
// Define the calling function name
cat /opt/name.txt // The command to call ( Parameters )
}
dxj // Call function name , Use the commands inside ( Parameters )
[[email protected] ~]# sh 2.sh
1 zhangsan
2 lisi
3 wangwu
# Format two :
Function name (){
Command sequence
}
#!/bin/bash
dxj(){
cat /opt/name.txt
}
dxj
## The most commonly used , Because the most concise
- After the function is defined, it will not execute automatically , You need to call , The advantage is that you can write a piece of function code as a function , If you need to call the definition directly, it doesn't matter even if there are syntax errors , If you don't call, you won't report an error
Of course, the ultimate purpose of writing functions is to call , In order to implement a function block
The return value of the function :
- return Represents the exit function and returns an exit value , You can use $? The variable displays the value
Usage principle :
- 1. Take the return value as soon as the function ends , because $? Variable returns only the exit status code of the last command executed
- 2. Exit status code must be 0~255, If the value exceeds the value, it will be the remainder 256
4.2 Function call
Directly define the code block of the function in the script and write the function name to complete the call
#!/bin/bash
dxj(){
// Defines a function called dxj
echo "this is a dxj" // The function is to print this is a dxj
}
dxj // Writing the function name directly will run the code in the function body
[[email protected] ~]# sh 2.sh
this is a dxj
Be careful 1: Function name must be unique , If you define a , Use the same name to define , The second will override the function of the first , There are results you don't want , So don't use the same name ( The function name can be consistent, but it can only be executed in different environments )
1 example :
[[email protected] ~]# vim 2.sh
#!/bin/bash
xtz (){
echo hello
}
xtz (){
echo world
}
xtz
[[email protected] ~]# sh 2.sh
world
Be careful 2: The function must be defined before calling
2 example :
#!/bin/bash
dxj (){
echo hello
}
xtz (){
echo world
}
he (){
echo "$(dxj) $(xtz)"
}
he
[[email protected] ~]# sh 2.sh
hello world
Be careful 3: You don't have to define the function at the beginning of the script , Just call the previously defined
- In case of nested calls in other places , You cannot write function values directly , Avoid being unable to recognize , You can use a reverse apostrophe , It is equivalent to the result of calling the function
3 example :
#!/bin/bash
dxj (){
echo hello
}
xtz (){
echo world
}
he (){
echo "`dxj` `xtz`" // If it's directly dxj and xtz Words , It won't print out hello world And it will be dxj xtz
}
he
[[email protected] ~]# sh 2.sh
hello world
4 example : Deploy local yum Source
[[email protected] ~]# vim yum.sh
#!/bin/bash
backuprepo (){
// Function name
cd /etc/yum.repos.d
mkdir repo,bak
mv *.repo repo.bak
mount /dev/sr0 /mnt &>/dev/null
}
makelocalrepo (){
echo
[local]
name=local
baseurl=file:///mnt
enable=1
gpgcheck=0 > local.repo
}
userlocalrepo (){
yum clean all > /dev/null
yum makecache > /dev/null
yum install -y httpd > /dev/null
}
backuprepo // call
makelocalrepo // call
userlocalrepo // call
4 example : Deploy local yum Source
[[email protected] ~]# vim yum.sh
#!/bin/bash
backuprepo (){
// Function name
cd /etc/yum.repos.d
mkdir repo,bak
mv *.repo repo.bak
mount /dev/sr0 /mnt &>/dev/null
}
makelocalrepo (){
echo
[local]
name=local
baseurl=file:///mnt
enable=1
gpgcheck=0 > local.repo
}
userlocalrepo (){
yum clean all > /dev/null
yum makecache > /dev/null
yum install -y httpd > /dev/null
}
backuprepo // call
makelocalrepo // call
userlocalrepo // call
边栏推荐
- 通过Xshell7使用rz,sz命令上传下载文件
- Interpretation of concurrent virtual users, RPS and TPS
- [solution] the local Group Policy Editor (gpedit.msc) in Win 11 cannot be opened
- Graduation thesis word skills Collection
- Chapter 1 - multi agent system
- DNS domain name resolution
- C语言回调函数 & sprinf 实际应用一例
- No, no, No. yesterday, someone really didn't write binary enumeration
- 深入性能测试数据分析
- Experience in using flow playback tool Gor
猜你喜欢
jmeter连接数据库的方法
10.系统安全及应用
Brief introduction of Feature Engineering and its implementation of sklearn
[solved] after referring to the local MySQL and forgetting the password, [server] --initialize specified but the data directory has files in it Aborti
NFS服务
WINRAR命令拷贝指定文件夹为压缩文件,调用计划任务进行备份。
Understand HTTP cache in 30 minutes
echo -e用法
Services for NFS
DNS域名解析
随机推荐
Getting to know Alibaba cloud environment construction for the first time: unable to connect remotely, and having been in the pit: the server Ping fails, FTP is built, the server builds the database,
How to do a good job of test case review
Lintcode 366:fibonacci Fibonacci sequence
Performance traffic playback
Next array - circular section
[unity development tips] unity mixer mixer controls global volume
Common English business mail phrases
The difference between cookies and sessions
BeanShell脚本获取当前时间
expect免交互
Subnet division (see details)
Inverse yuan (I'll add these words if there are too many people using the name)
Use of sqlmap
Response assertion of JMeter interface test
After unity imports the FBX model, the rotation and position of the object will change automatically at runtime
[antv G2] how to solve the memory leak caused by G2
MySQL差删改查用户登录修改密码
Server knowledge (details)
Shortest circuit / secondary short circuit /k short circuit
GoReplay