Directory
I. Condition selection: If statement
Two. Conditional judgment: Case statement
Three. For loop
I. Condition selection: If statement
Single Branch
if judgment condition; then
Branch code with true condition
Fi
Example: Judging whether a number equals 10
#!/bin/bash read -p ‘输入一个数字‘ num if [ $num -eq 10 ];then echo 该数字等于10 fi
Dual Branch
if judgment condition; Then condition is true for the branch code
Else condition is a false branch code
Fi
Example: Judging if a number is greater than 10
#!/bin/bash read -p ‘输入一个数字‘ num if [ $num -gt 10 ];then echo 该数字大于10 else echo 该数字不大于10 fi
Multiple branches
if judgment condition 1; Then condition is true for the branch code
Elif judgment Condition 2; Then condition is true for the branch code
Elif judgment Condition 3; Then condition is true for the branch code
Else the above conditions are false branch codes
Fi
Example: Judging the range of a number
#!/bin/bash read -p ‘输入一个数字‘ num if [ $num -lt 10 ];then echo 该数字小于10 elif [ $num -ge 10 -a $num -lt 20 ];then echo 该数字大于等于10小于20 elif [ $num -ge 20 -a $num -lt 50 ];then cho 该数字大于等于20小于50 else echo 该数字大于等于50 fi
Two. Conditional Judgment Case Statement
Case $ variable name in
Condition 1)
branch 1;;
Condition 2)
branch 2;;
Default condition *)
Default Branch;;
Esac
After each condition followed by) the end of each branch with;; End
Example
Write a script that can judge Yes/no, (the case can be recognized, yes nine kinds of possible, no four kinds of possible),
#!/bin/bash read -p "请输入yes|no: " q case $q in [Yy][Ee][Ss]|[Yy]) echo "yes";; [Nn][Oo]) echo "no";; *) echo "请输入正确的格式" esac
Three. For loopExecution mechanism: 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
For variable name in list;
Loop body
Done
Example 1 calculates the sum of 1 to 10 of all positive integers using a for loop
#!/bin/bash let s=0 for n in echo {1..10};do s=$[$s+$n] echo $s done
Example 2 printing a 99 multiplication table with a for loop
#!/bin/bash for i in {1..9};do for n in `seq 1 $i`;do echo -n -e " $i"x"$n=$[i*n] " done echo done(每一个for要对应一个done)
The use of if,case,for in shell scripts