The commonly used loops have a for loop and a while loop.
- For loop
[email protected] sbin]# cat for.sh#! /bin/bashfor i in ' seq 1 5 '; Do Echo $idone
A sequence in the script that seq 1 5
represents from 1 to 5. You can run this command directly and try it. The result of the script execution is:
[Email protected] sbin]# sh for.sh12345
With this script you can see the basic structure of the For loop:
The condition of the for variable name in the loop; do Commanddone
The "condition of the loop" here can be written as a set of strings or numbers (separated by 1 or more spaces), or it can be the result of a command's execution:
[[email protected] sbin]# for I in 1 2 3 a B; do echo $i; Done123ab
You can also write the execution results of a reference system command, just like that seq 1 5
but need to be enclosed in anti-quotes:
[[email protected] sbin]# for file in ' ls '; do echo $file; donecase.shfirst.shfor.shif1.shif2.shif3.shoption.shread.shsum.shvariable.sh
- While loop
[email protected] sbin]# cat while.sh#! /bin/basha=5while [$a-ge 1]; Do echo $a a=$[$a -1]done
The while loop format is also simple:
while condition; do Commanddone
The above example script performs the following results:
[Email protected] sbin]# sh while.sh54321
Alternatively, you can replace the loop condition with a colon, so that you can do a dead loop and often write a monitoring script like this:
While:; Do command sleep 3done
Functions in a shell script
The function is to organize a piece of code into a small unit, and give the small unit a name, when the code is used to call the name of the small unit directly. Sometimes a piece of code in a script is always reused, and if it is written as a function, it can be replaced with a function name each time it is used, saving time and space.
[email protected] sbin]# cat func.sh#! /bin/bashfunction sum () { sum=$[$1+$2] echo $sum}sum
The results of the implementation are as follows:
[[Email protected] sbin]# sh func.sh 1 23
The sum () in func.sh is a custom function in which the shell script function is formatted as:
Function name () {command}
In the shell script, the function must be written in the first, not in the middle or the last, because the function is to be called, if it has not yet been called, it will certainly be wrong.
Loops in a shell script