Bash控制结构
1. if-else语句
#!/bin/bash #if ... fi 语句; if [ $a != $b ] then echo "a != b" fi #if ... else ... fi 语句; if [ $a == $b ] then echo "a is equal to b" else echo "a is not equal to b" fi #if ... elif ... else ... fi 语句; if [ $a == $b ] then echo "a is equal to b" elif [ $a -gt $b ] then echo "a is greater than b" elif [ $a -lt $b ] then echo "a is less than b" else echo "None of the condition met" fi
2. case-esac语句
#!/bin/bash read -p "Please input a number" aNum case $aNum in 1) echo 'You select 1' ;; #不要忘记加上这一行 2) echo 'You select 2' ;; 3) echo 'You select 3' ;; 4) echo 'You select 4' ;; *) echo 'You do not select a number between 1 to 4' ;; esac
3. for循环
#!/bin/bash #for循环一般格式为: #for 变量 in 列表 #do # command1 # command2 # ... # commandN #done #列表是一组值(数字、字符串等)组成的序列,每个值通过空格分隔。每循环一次,就将列表中的下一个值赋给变量。 #in 列表是可选的,如果不用它,for 循环使用命令行的位置参数。 #for loop in 1 2 3 4 5 for loop in 1 2 tt 4 5 kk do echo "The value is: $loop" done #The value is: 1 #The value is: 2 #The value is: tt #The value is: 4 #The value is: 5 #The value is: kk num=0 for str in 'This is a string' do num=`expr $num + 1` echo $str $num #-->This is a string 1 ;只执行一次 done
4. while循环
#!/bin/bash COUNTER=0 while [ $COUNTER -lt 3 ] do COUNTER=`expr $COUNTER + 1` done
5. until循环
#!/bin/bash #until 循环执行一系列命令直至条件为 true 时停止。until 循环与 while 循环在处理方式上刚好相反。一般while循环优于until循环,但在某些时候,也只是极少数情况下,until 循环更加有用。 a=0 until [ ! $a -lt 5 ] do echo $a #--> 0 1 2 3 4 5 a=`expr $a + 1` done
6. break,continue跳出循环