Shell中的for迴圈總結_linux shell

來源:互聯網
上載者:User

關於shell中的for迴圈用法很多,一直想總結一下,今天網上看到上一篇關於for迴圈用法的總結,感覺很全面,所以就轉過來研究研究,嘿嘿...

複製代碼 代碼如下:
for((i=1;i<=10;i++));do echo $(expr $i \* 4);done

在shell中常用的是 for i in $(seq 10)
複製代碼 代碼如下:

for i in `ls`
for i in ${arr[@]}
for i in $* ; do
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
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.使用`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 1 10000000做遞增,之前用這種方法的時候沒遇到問題,因為之前的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==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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.