shell中for循环总结

shell中的for循环用法的总结:

1、

 for((i=1;i<=10;i++));do echo $(expr $i \*4);done
for (( i=0; i<10; i++)); do
echo $i
done
for (()) 方式并不是总是好使,在busybox的ash中就会报 syntax error, 所以还是建议用下面的for循环用法

2、在shell中常用的是 for i in $(seq 10)

for File in /proc/sys/net/ipv4/conf/*/accept_redirects; do
echo $File
done
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:'

for File in /proc/sys/net/ipv4/conf/*/accept_redirects; do
echo $File
done
echo "直接指定循环内容"

for i in f1 f2 f3 ;do
echo $i
done

---------------------------------------------------------------------------------------------------------

shell中for循环用法
shell语法好麻烦的,一个循环都弄了一会 ,找了几个不同的方法来实现输出1-100间可以被3整除的数
1.用(())

#!/bin/bash
clear

for ((i=1;i<100;i++))
        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))
do
        if (($i%3==0))
        then
                echo $i
        fi
        i=$(($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 ]
        do
                echo $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 $i
                if [ $i -ge 10 ]; then
                        break
                fi
done
}

function test_continue(){
        i=1
        for i in $(seq 100); do
                if (( i%10==0 )); then
                        echo $i
                        continue
                fi
        done
}

echo "test_while..."
test_while

echo "test_for..."
test_for

echo "test_continue..."
test_continue
运行结果:
$ ./example.sh
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


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值