linux shell脚本使用结构化命令(2)
1 for var in list 2 do 3 commands 4 done
1 oracle@suse:~/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 oracle@suse:~/testshell> ./fortest.sh 10 the city is beijing 11 the city is shanghai 12 the city is shenzhen 13 the city is dalian
一种c语言风格的for命令
1 for (( variable assignment ; condition ; iterationprocess )) 2 do 3 commands 4 done
1 oracle@suse:~/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 done 11 echo sum= $sum 12 13 for (( a=1,b=1;a<5,b<3;a++,b++ )) 14 do 15 (( c = a + b )) 16 echo c = $c 17 done 18 oracle@suse:~/testshell> ./fortest.sh 19 sum= 5050 20 c = 2 21 c = 4
1 while test command 2 do 3 other commands 4 done
1 oracle@suse:~/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 = $var 11 done 12 oracle@suse:~/testshell> ./whiletest.sh 13 var = 2 14 var = 1 15 var = 0
1 until test commands 2 do 3 other commands 4 done
1 oracle@suse:~/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 = $var 11 done 12 oracle@suse:~/testshell> ./untiltest.sh 13 var = 6 14 var = 7 15 var = 8 16 var = 9
还有一点就是循环输出可以输出到屏幕,也可以输出到文件,就是在done命令后加个处理命令
1 oracle@suse:~/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 = $var 11 done > result.txt 12 oracle@suse:~/testshell> ./untiltest.sh 13 oracle@suse:~/testshell> ls 14 untiltest.sh result.txt 15 oracle@suse:~/testshell> cat result.txt 16 var = 6 17 var = 7 18 var = 8 19 var = 9
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。