1. shell flow control
2. for statement
3. while statement
4. break and continue statements
5. case statement
6. shell programming advanced combat
shell flow control
Flow control is an instruction to change the running order. linux shell have its own flow control statements, including conditional statements (IF), loop (for, while), select statement (case). Now I will introduce by the following example, each statement to use
The if statement
format:
格式:if list; then list; [ elif list; then list; ] ... [ else list; ] fi
1.1 single branch
if the conditional expression; then
command
fi
Example:
#!/bin/bash N=10 if [ $N -gt 5 ]; then echo yes fi # bash test.sh yes
1.2 pairs of branch
if the conditional expression; then commands else commands fi
Example 1:
#!/bin/bash N=10 if [ $N -lt 5 ]; then echo yes else echo no fi # bash test.sh no
Example 2: determine whether the process is running crond
-v: invert representation
-c: i.e. COUNT, substituted normal output, the number of display lines
#!/bin/bash NAME=crond NUM=$(ps aux | grep $NAME | grep -vc grep) if [ $NUM -eq 1 ]; then echo "$NAME running." else echo "$NAME is not running!" fi
Example 3: Check whether the host is online
-c: send a few packets indicate
-w: represents the waiting time. When attempting to detect unreachable hosts This option is useful.
#!/bin/bash if ping -c 1 192.168.1.1 &>/dev/null; then
echo "OK." else echo "NO!" fi
if statements can directly determine the status of the command, eliminating the need to obtain $? this step!
More than 130 branches
if the conditional expression; then commands elif conditional expression; then commands else commands fi
When the conditions are met unsure which one can judge the condition known written, do the appropriate treatment.
Example 1:
$ 1: that accept user input parameters
#!/bin/bash N=$1 if [ $N -eq 3 ]; then echo "eq 3" elif [ $N -eq 5 ]; then echo "eq 5" elif [ $N -eq 8 ]; then echo "eq 8" else echo "no" fi
If the first condition is met will no longer match down.
The shell programming if statement of actual cases
demand:
1. The user input is completed automatically copy a file or directory, and enabling user to specify the position of the copy destination.
2. The user experience is good.
#!/bin/bash read -p "pls enter a file you want to copy:" file if [ -f $file -o -d $file ];then read -p "do you want to copy the $file?(y/n)" sure
confirm=$(echo ${sure} | tr A-Z a-z) if [ "$confirm" == "y" ];then read -p "where do you want to copy?" dire if [ -d $dire ];then cp -a $file $dire echo "the $file copied to $dire" else echo "the $dire is not exists" exit 1 fi elif [ "$confirm" == "n" ];then echo "bye" else echo "pls input y or n" fi else echo "the $file is not exists" fi
Exercise 1: trying to write a shell simple calculator, to achieve Math.
Please enter a number: 7
Please enter operators: +
Enter the second number: 7
7+7=14
Exercise 2: Enter a user with a script judge to determine whether the user exists.
for statement
格式:for name [ [ in [ word ... ] ] ; ] do list ; done
The value for the variable name in the list; do command done
or
The value for the variable name in the list
do
command
done
Example 1:
#!/bin/bash for i in {1..3}; do echo $i done # bash test.sh 1 2 3
Example 2: Calculation 100 within the even and
#!/bin/bash sum=0 for i in `seq 2 2 100` do let sum+=$i done echo "$sum"
shell programming for the statement of actual cases
demand:
1. Check the current batch classroom host is online
#!/bin/bash . /etc/init.d/functions ip=192.168.7. for i in {100..150} do if ping -c 1 -w 1 $ip$i &>/dev/null;then echo -n "$ip$i在线!" success echo "" else echo -n "$ip$i不在线!" failure echo "" fi done
Exercise 1: Calculate the odd and less than 100
Exercise 2: judgment / root directory of the file type
while statement
The condition is true then enter an infinite loop; the condition is false the loop exits
格式:while list; do list; done
while the conditional expression; do command done
Example 1:
#!/bin/bash N=0 while [ $N -lt 5 ]; do let N++ echo $N done # bash test.sh 1 2 3 4 5
When the conditional expression is false, the loop is terminated.
Example 2: conditional expression is true, it will have an infinite loop
#!/bin/bash while [ 1 -eq 1 ]; do echo "yes" done
It can also be used directly conditional expressions true:
#!/bin/bash while true; do echo "yes" done
What is the role that an infinite loop?
Script can be used to detect background, The following is a split brain detection script
We only need to enter nohup bash naolie.sh & runs continuously in the background to the script on the command line
Example 1: Detection of split brain
#!/bin/bash while true do ip=`ip a s eth0 | awk -F " +" 'NR==4{print $3}' | awk -F "/" '{print $1}' | awk -F "." '{print $4}'`1 ping -c 3 -i 1 -W 1 10.220.5.166 &>/dev/null if [ $? -eq 0 ] && [ $ip = 1001 ];then echo "happed naolie" else echo "everything is ok" fi done
Example 2: detection of the number of terminals
! # / bin / bash the while to true do NUM = `the WHO | WC -l` echo" is the number of terminals currently open: $ NUM " SLEEP 5 DONE
To use a while loop to read line by line a.txt file, there are three ways:
Mode 1:
#!/bin/bash cat ./a.txt | while read LINE; do echo $LINE done
Option 2:
#!/bin/bash while read LINE; do echo $LINE done < ./a.txt
Mode 3:
exec <./a.txt # reads the standard output file as the while the LINE Read; do echo $ the LINE DONE
And until there is a statement while the associated, while it differs at only when the conditional expression is false cycle, the actual use is relatively small, no more explanation here.
#!/bin/bash n=0 until [ $n -eq 5 ] do let n++ echo "$n" done
break and continue statements
break the cycle is terminated.
continue is out of the current cycle.
Example 1: in an endless loop, loop termination condition is satisfied
#!/bin/bash N=0 while true; do let N++ if [ $N -eq 5 ]; then break fi echo $N done # bash test.sh 1 2 3 4
If the determination with which, and with the break statement, which is out of the loop. There associated with a continue statement, it is out of this cycle.
Example 2: Give an example of usage continue
#!/bin/bash N=0 while [ $N -lt 5 ]; do let N++ if [ $N -eq 3 ]; then continue fi echo $N done # bash test.sh 1 2 4
When the variable N is equal to 3, continue this cycle is skipped without performing the following single echo.
Note: continue and break statement can only be used in the loop.
[root@ken-node1 ~]# cat test.sh #!/bin/bash st=0 while true do let st++ if [ $st -eq 5 ];then continue elif [ $st -eq 10 ];then break else echo "$st" fi done [root@ken-node1 ~]# bash test.sh 1 2 3 4 6 7 8 9
case statement
Usually case statement for selectively performing the command corresponding to the partial block.
case schema name in mode 1) command ;; mode 2) command ;; *) do not meet the above command execution mode esac
Each pattern must end with a right parenthesis, the end of the command ends with a double semicolon, the last one will not need to add ;;.
Example 1: The location parameter matching different modes
#!/bin/bash case $1 in start) echo "start." ;; stop) echo "stop." ;; restart) echo "restart." ;; *) echo "Usage: $0 {start|stop|restart}" esac # bash test.sh Usage: test.sh {start|stop|restart} # bash test.sh start start. # bash test.sh stop stop. # bash test.sh restart restart.
Example 2:
#!/bin/bash case $1 in [0-9]) echo "match number." ;; [a-z]) echo "match letter." ;; '-h'|'--help') echo "help" ;; *) echo "Input error!" exit esac # bash test.sh 1 match number. # bash test.sh a match letter. # bash test.sh -h help # bash test.sh --help help
Regular mode support has: *,, [], [.-.], |?. There are separate sections explain later Shell regular expressions.
Advanced real shell programming
Real 1: Write a little guessing game
Claim:
1. Quit guess
2. random numbers
3. Use good experience
#!/bin/bash clear num=`echo $RANDOM` count=0 while true do let count++ read -p "pls enter a num you guess:" guessnum if [ $guessnum -lt $num ]; then echo "the num is so smaller!" elif [ $guessnum -gt $num ];then echo "the num is so bigger!" elif [ $guessnum -eq $num ];then echo "right!wonderful! " break else echo "good bye" exit fi done echo -e "\033[36myou guess $count times\033[0m"# -E allows backslash character escapes listed below will be explained.
Combat 2: detects the current IP address of the online classroom
Claim:
1. Display appearance
#!/bin/bash . /etc/init.d/functions ip=172.20.10. for i in {1..255} do if ping -c 1 $ip$i &>/dev/null ;then echo -n "$ip$i" #-n表示不输出行尾的换行符 success echo "" else echo -n "$ip$i" failure echo "" fi done
Combat 3: Check the package is installed
Claim:
1. Enter the name of the software the user can query
#!/bin/bash read -p "pls enter a softname:" softname if rpm -q $softname &>/dev/null ;then echo "the $softname is already installed" else echo "the $softname" is not installed fi
Combat 4: print multiplication table
#!/bin/bash for i in `seq 9` do for a in `seq 9` do if [ $a -le $i ];then echo -n "$a*$i=$(($i*$a)) " fi done echo "" done
Supplementary exercises
1. simple calculator (addition, subtraction)
! # / bin / the bash Read -p "Please enter the first digit:" A Read -p "Please enter the operator [+ - * /]:" B Read -p "Please enter the second digit:" C IF [-n "$ A" -a -n "$ B" -a -n "$ C"]; the then IF [ "$ B" == "+"]; the then echo "$ + $ A $ C = (( A + $ C $)) " elif [" $ B "==" - "]; the then echo" $ A- $ C = $ (($ A- $ C)) " elif [" $ B "==" * "]; the then echo" $ A $ * $ C = ((A * $ C $)) " elif [" $ B "==" / "]; the then echo" A $ / $ C = $ (($ A / $ c)), " the else echo" Please enter the + - *% " fi the else echo "Please enter the content as required!" fi
2. Create a Batch 100 begins with a number of files, and outputting a second to every terminal
#!/bin/bash for i in {1..100} do touch ${i}.txt echo "${i}.txt" sleep 1 done
3. Dynamic continuous monitoring of the remaining amount of native linux system memory (display values only), and an output terminal
#!/bin/bash while true do mem=`free -h | grep "Mem" | cut -d "M" -f 4 | tr -d " "` echo $mem sleep 1 done