標籤:
一.for命令
二.while命令
三.until命令
1.for命令基本格式
1 for var in list2 do3 commands4 done
1 [email protected]:~/testshell> cat fortest.sh 2 #!/bin/bash 3 #test for command 4 5 for city in beijing shanghai shenzhen dalian 6 do 7 echo the city is $city 8 done 9 [email protected]:~/testshell> ./fortest.sh 10 the city is beijing11 the city is shanghai12 the city is shenzhen13 the city is dalian
一種c語言風格的for命令
1 for (( variable assignment ; condition ; iterationprocess ))2 do3 commands4 done
1 [email protected]:~/testshell> cat fortest.sh 2 #!/bin/bash 3 #test for command 4 5 sum=0 6 for (( i=1;i<=100;i++ )) 7 do 8 (( sum = sum + i )) 9 10 done11 echo sum= $sum12 13 for (( a=1,b=1;a<5,b<3;a++,b++ ))14 do15 (( c = a + b ))16 echo c = $c17 done18 [email protected]:~/testshell> ./fortest.sh 19 sum= 505020 c = 221 c = 4
2.while命令基本格式
1 while test command2 do3 other commands4 done
1 [email protected]:~/testshell> cat whiletest.sh 2 #!/bin/bash 3 #test while command 4 5 var=3 6 7 while [ $var -gt 0 ] 8 do 9 (( var = var -1 ))10 echo var = $var11 done12 [email protected]:~/testshell> ./whiletest.sh 13 var = 214 var = 115 var = 0
3.until命令基本格式
1 until test commands2 do3 other commands4 done
1 [email protected]:~/testshell> cat untiltest.sh 2 #!/bin/bash 3 #test until command 4 5 var=5 6 7 until [ $var -gt 8 ] 8 do 9 (( var++ ))10 echo var = $var11 done12 [email protected]:~/testshell> ./untiltest.sh 13 var = 614 var = 715 var = 816 var = 9
還有一點就是迴圈輸出可以輸出到螢幕,也可以輸出到檔案,就是在done命令後加個處理命令
1 [email protected]:~/testshell> cat untiltest.sh 2 #!/bin/bash 3 #test until command 4 5 var=5 6 7 until [ $var -gt 8 ] 8 do 9 (( var++ ))10 echo var = $var11 done > result.txt12 [email protected]:~/testshell> ./untiltest.sh 13 [email protected]:~/testshell> ls14 untiltest.sh result.txt 15 [email protected]:~/testshell> cat result.txt 16 var = 617 var = 718 var = 819 var = 9
linux shell指令碼使用結構化命令(2)