Shell:Shell 流程式控制制詳情,shell流程式控制制詳情
Shell:Shell 流程式控制制詳情if else
if語句
文法:
if conditionthen command ...fi
eg:
#!/bin/basha=100b=100if [ $a == $b ]then echo "$a == $b"fi
輸出:
100 == 100
也可以在終端寫成一行:
[zhang@localhost ~]$ a=100[zhang@localhost ~]$ b=100[zhang@localhost ~]$ if [ $a == $b ]; then echo "$a == $b"; fi100 == 100
if else語句
文法:
if conditionthen command ...else command ...fi
eg:
在終端輸入
[zhang@localhost ~]$ a=100[zhang@localhost ~]$ b=200[zhang@localhost ~]$ if [ $a == $b ]> then> echo "$a == $b"> else> echo "$a != $b"> fi100 != 200
if elif else語句
文法:
if condition1then command1 ...elif comdition2then command2else commandfi
eg:
#!/bin/basha=100b=200c=150if [ $[a + c] > $b ]then echo "$a + $c > $b return true"elif [ $[a + c] < $b ]then echo "$a + $c < $b return true"else echo "$a + $c = $b return true"fi
輸出結果:
100 + 150 > 200 return true
for迴圈
for文法:
for var in item1 item2 ... itemndo command1 command2 ... commandndone
寫成一行:
for var in item1 item2 ... itemn; do command1;command2 ... done;
eg:
[zhang@localhost ~]$ for num in 1 2 4 8 16> do> echo $num> done124816
一行執行:
[zhang@localhost ~]$ for num in 1 2 3 4 5; do echo $num; done12345
While語句
while文法:
while conditiondo commanddone
eg:
#!/bin/bashnum=1while(($num<=5))do echo $num let "num++"done
輸出結果:
12345
無限迴圈
while :do commanddone
或者
while truedo commanddone
或者
for (( ; ; ))
until迴圈
until文法:
until condiiondo commanddone
一般使用while替代
case
case文法:
case value invalue1) command1 command2 ... commandn ;;value2) command1 command2 ... commandn ;;value3) command1 command2 ... commandn ;;*) command1 command2 ... commandn ;;esac
;;:其間所有command執行到;;結束。相當於break。
*:相當於java中的default。
eg:
#!/bin/bashvalue=2case $value in1) echo "$value equal 1" ;;2) echo "$value equal 2" ;;3) echo "$value equal 3" ;;*) echo "$value not find" ;;esac
輸出結果:
2 equal 2
跳出迴圈
break命令
#!/bin/bashfor i in 1 2 3 4 5do if [ $[i % 2] == 0 ] then echo "$i" break fidone
輸出:2
continue命令
#!/bin/bashfor i in 1 2 3 4 5do if [ $[i % 2] == 0 ] then echo "$i" continue fidone
輸出:
24
esac命令
與case協同使用,作為case的結束符號。