关于shell中的for循环用法很多,一直想总结一下,今天网上看到上一篇关于for循环用法的总结,感觉很全面,所以就转过来研究研究,嘿嘿…
1、 for((i=1;i<=10;i++));do echo
(expr
i *4);done
2、在shell中常用的是 for i in $(seq 10)
3、for i in ls
4、for i in ${arr[@]}…
5、for i in $* ; do
6、for File in /proc/sys/net/ipv4/confaccept_redirects:’
18.for File in /proc/sys/net/ipv4/conf/*/accept_redirects; do
19.echo
File20.done21.echo“直接指定循环内容”22.foriinf1f2f3;do23.echo
i
24.done
25.echo
26.echo “C 语法for 循环:”
27.for (( i=0; i<10; i++)); do
28.echo $i
29.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.使用seq 100
#!/bin/bash
clear
for i in seq 100
do
if((i%3==0))
then
echo $i
continue
fi
done
3.使用while
#!/bin/bash
clear
i=1
while((
i<100))doif((
i%3==0))
then
echo
ifii=
(($i+1))
done
在shell用for循环做数字递增的时候发现问题,特列出shell下for循环的几种方法:
1.
for i in seq 1 1000000
;do
echo $i
done
用seq 110000000做递增,之前用这种方法的时候没遇到问题,因为之前的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.
for i in {1..10000000;do
echo $i
done
其实选用哪种方法具体还是得由相应的shell环境的支持,达到预期的效果,再考虑速度方面的问题。
示例:
#!/bin/sh
i=1
function test_while(){
i=1
while [
i]doecho
i
i=expr $i + 1
if [ $i -ge 10 ];
then
break
fi
done
}
function test_for(){
i=1
for ((i=1; i<=100;i++)); do
echo
iif[
i -ge 10 ]; then
break
fi
done
}
function test_continue(){
i=1
for i in
(seq100);doif((i==0));thenecho
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