Shell scripts become used in the process usually requires process control, in general, sequential execution, in the actual use of different situations need to execute different commands, then use the choice to execute such as if, case, sometimes need to repeatedly execute, loop execution such as for, while, until
Conditional Select EXECUTE statement if
Single Branch |
Dual Branch |
if judgment condition; then Branch code with true condition Fi |
if judgment condition; Then Branch code with true condition Else The condition is a false branch code Fi |
[Email protected] ~]# vim score.sh 1 #!/bin/bash 2 read-p "Please input you score:" Score 3 if [$score-eq N 4 echo "excellent" 5 elif[$score-ge];then 6 echo "Keep Tring" 7 fi
Conditional Judgment Statement case
Case variable reference in
PAT1) Branch 1 ;; PAT2) Branch 2 ;; *) Default Branch ;; Esac |
Example: Scripting/root/bin/yesorno.sh, prompting the user to enter Yes or no, and to determine whether the user entered Yes or no, or other information
[Email protected] ~]# cat/bin/yesorno.sh #!/bin/bashread-p "Marry me? Please answer yes or no: "Anscase $ANS in[yy][ee][ss]| [Yy]) echo "Me too";; [Nn] [oo]| [Nn]) echo "My heart broken";; *) echo "Once again" Esac
Loop Execution Statement
For loop number of cycles known beforehand
Assigns the element in the list to the "variable name" in turn; The loop body is executed once each assignment; Until the elements in the list are exhausted, the loop ends
Method One |
Method Two: Special format |
For variable name in list; Loop body Done |
for (initialize EXP1; conditional judgment EXP2; control variable correction expression EXP3)) Loop body Done
|
Example: Writing a script that prompts for the value of a positive integer n to calculate the sum of 1+2+...+n
Method One: #!/bin/bashread-p "Please input positive integer:" Nsum=0for i in ' seq 1 $n ' do sum=$[$sum + $i]done echo $sum method two: [Email protected] ~]# vim sum.sh #!/bin/bashread-p "Please input positive integer:" Nsum=0for ((i=1;i<= $n; i++)) sum=$[$sum + $i]done echo $sum
While loop number is unknown in advance
CONDITION: cyclic control conditions; Before entering the cycle, make a judgment; once each loop is judged again; the condition is "true", then a loop is executed until the condition test state is "false" to terminate the loop
Therefore: Condtion generally should have a cyclic control variable, and the value of this variable will be continuously corrected in the loop body
Enter condition: Condition is true
Exit Condition: Condition is false
Usage One: |
Usage Two: A special usage of the while loop (traversing each line of the file) |
While Cmd;d o Cmdn ... Done |
while read line; Do
Loop body Done </path/from/somefile Note: Read each line in the/path/from/somefile file sequentially and assign the row to the variable line |
Example: Write a script that asks for the sum of all positive odd numbers within 100
[[email protected] ~]# vim score.sh 1 #!/bin/bash 2 Sum=0;i=1 3 while ((I<100)) 4 do 5 sum=$[$sum + $i] 6 let i=$[$i +2] 7 done 8 echo "sum= $sum"
Example: Scan each line of the/etc/passwd file, if the Gecos field is found to be empty, populate the user name and the unit phone, and prompt the user for Gecos information to be modified successfully.
#!/bin/bashwhile Read line;d o comment= ' echo $line |cut-d:-f5 ' username= ' echo $line |cut-d:-f1 ' If [-Z ' $c Omment "];then chfn-f" $username "$username &>/dev/null chfn-p" 0371-61703300 "$username & >/dev/null Fidone </APP/PASSWD
Until loops have entry conditions and exit conditions
Entry condition: CONDITION is False
Exit Condition: CONDITION is True
Until CONDITION; Do Loop body Done |
Example: Write a script that asks for the sum of all positive odd numbers within 100
[Email protected] ~]# vim score.sh 1 #!/bin/bash 2 Sum=0;i=1 3 until ((I>100)) 4 do 5 sum=$[$sum + $i] 6 let i=$[$i +2] 7 done 8 echo "sum= $sum"
Select Loop statement
The Select loop is used primarily to create menus, and menu items in numerical order are displayed on standard errors, and the PS3 prompt is displayed.
Wait for user input
Select is an infinite loop, so remember to exit the loop with the break command, or terminate the script with the Exit command. You can also press CTRL + C to exit the loop
The user enters a number in the menu list and executes the corresponding command
User input is saved in the built-in variable REPLY
Select variable in list Do Circular Body Command Done |
Loop Control statement Continue
Continue [n]: Early end of the nth layer of the current cycle, and directly into the next
The inner layer is the 1th floor.
While CONDTIITON1; Do CMD1 ... if CONDITION2; Then Continue Fi Cmdn ... Done |
Loop control Statement Break
Break [n]: Early end of the nth layer cycle, the inner layer is the 1th layer
While CONDTIITON1; Do CMD1 ... if CONDITION2; Then Break Fi Cmd |
Homework:
1, write a script, prompted to enter a network address, such as 192.168.0.0, determine the input network segment host online status, and statistics online and offline host how much
[[email protected] ~]# vim ping.sh#!/bin/bashread -p "please input network (eg:192.168.0.0): " netecho $net |egrep " ([0-9]|[ 1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]). {3} [0-9]| [1-9] [0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-4] " &> /dev/null if [ $? -eq 0 ];then netip= ' echo $net |egrep -o ". *\." ' for ( i=1;i<255;i++ );d o { ping -c 1 -w1 $netip $i &>/dev/null if [ $? -eq 0 ];then echo "$netip $i is up " echo " $netip $ I " >> /app/${netip}txt; fi }& done else echo "Please input correct format " fi
2, scripting, printing chess board
#!/bin/bashyellow= "\033[1;43m \033[0m" red= "\033[1;44m \033[0m "for i in {1..8} ; do if [ $[i%2] -eq 0 ] ; then for j in {1..4} ; do echo -en "$yellow $red" done else for j in {1..4} ; do echo -en "$red $yellow" done fi echodone
3, find a reject link that has more than 10 connections
Method One: Only a link greater than 10 times can be processed #!/bin/bashcheckinterval=30while true ;d o link= ' netstat -nt | sed -rn '/^tcp/s/.* (. *):. *$/\1/p ' |sort |uniq -c | Sort -nr |head -n 1 ' linknum= ' echo $link |cut -d " " -f1 ' ip= ' echo $link |cut -d " " -f2 ' [ $linknum -ge 10 ]&& iptables -a innput -s -$ip -j REJECT echo "$ip at ' date + '%F %t ' is reject ' >> /app/checknet.log sleep $ Checkintervaldone method Two: When there are more than 10 times the link can be processed #!/bin/bashwhile true ;d o link= ' netstat -nt | sed -rn '/^tcp/s/.* (. *):. *$/\1/p ' |sort |uniq -c | Sort -nr ' echo ' $linK "|while read fileline ;d o linknum= ' echo $link |cut -d " " -f1 ' ip= ' echo $link |cut -d " " -f2 ' if [ $linknum -ge 10 ];then iptables -a input -s -$ip -j REJECT echo "$ip at ' date + '%f %t ' is reject " > > /app/checknet.log fi done
Shell Script Process Control