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 ' Enter a number ' num
If [$num-eq];then
echo This number equals 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 ' Enter a number ' num
If [$num-gt];then
echo this number is greater than 10
Else
echo this number is not greater than 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 $变量名 in 条件1) 分支1;; 条件2) 分支2;; 默认条件 *) 默认分支;; esac 每个条件后面跟 )结尾 每个分支后面以 ;; 结束 例子 写一个能判断yes/no的脚本,(大小写均能识别,yes九种可能,no四种可能)、 #!/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};d o
S=$[$s + $n]
Echo $s
Done
Example 2 printing a 99 multiplication table with a for loop
#!/bin/bash
For i in {1..9};d o
For n in seq 1 $i
;d o
Echo-n-E "$i" x "$n =$[i*n]"
Done
Echo
Done
(每一个for要对应一个done)
The use of if,case,for in shell scripts