Shell中的for循环总结
关于shell中的for循环用法很多,一直想总结一下,今天网上看到上一篇关于for循环用法的总结,感觉很全面,所以就转过来研究研究,嘿嘿...
for((i=1;i<=10;i++));doecho$(expr$i\*4);done
在shell中常用的是foriin$(seq10)
foriin`ls` foriin${arr[@]} foriin$*;do forFilein/proc/sys/net/ipv4/confaccept_redirects:' forFilein/proc/sys/net/ipv4/conf/*/accept_redirects;do echo$File done echo"直接指定循环内容" foriinf1f2f3;do echo$i done echo echo"C语法for循环:" for((i=0;i<10;i++));do echo$i done
---------------------------------------------------------------------------------------------------------
shell中for循环用法
shell语法好麻烦的,一个循环都弄了一会,找了几个不同的方法来实现输出1-100间可以被3整除的数
1.用(())
#!/bin/bash clear for((i=1;i<100;i++)) for do if((i%3==0)) then echo$i continue fi done
2.使用`seq100`
#!/bin/bash clear foriin`seq100` do if((i%3==0)) then echo$i continue fi done
3.使用while
#!/bin/bash clear i=1 while(($i<100)) do if(($i%3==0)) then echo$i fi i=$(($i+1)) done
--------------------------------------------------------------------------------------------------------
在shell用for循环做数字递增的时候发现问题,特列出shell下for循环的几种方法:
1.
foriin`seq11000000`;do echo$i done
用seq110000000做递增,之前用这种方法的时候没遇到问题,因为之前的i根本就没用到百万(1000000),因为项目需要我这个数字远大于百万,发现用seq数值到1000000时转换为1e+06,根本无法作为数字进行其他运算,或者将$i有效、正确的取用,遂求其他方法解决,如下
2.
for((i=1;i<10000000;i++));do echo$i done 3. i=1 while(($i<10000000));do echo$i i=`expr$i+1` done
因为本方法调用expr故运行速度会比第1,第2种慢不少不过可稍作改进,将i=`expr$i+1`改为i=$(($i+1))即可稍作速度的提升,不过具体得看相应shell环境是否支持
4.
foriin{1..10000000;do echo$i done
其实选用哪种方法具体还是得由相应的shell环境的支持,达到预期的效果,再考虑速度方面的问题。
示例:
#!/bin/sh i=1 functiontest_while(){ i=1 while[$i] do echo$i i=`expr$i+1` if[$i-ge10];then break fi done } functiontest_for(){ i=1 for((i=1;i<=100;i++));do echo$i if[$i-ge10];then break fi done } functiontest_continue(){ i=1 foriin$(seq100);do if((i==0));then echo$i continue fi done } echo"test_while..." test_while echo"test_for..." test_for echo"test_continue..." test_continue
运行结果:
test_while... 1 2 3 4 5 6 7 8 9 test_for... 1 2 3 4 5 6 7 8 9 10 test_continue... 10 20 30 40 50 60 70 80 90 100