歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> SHELL編程 >> shell for參數

shell for參數

日期:2017/3/1 9:55:00   编辑:SHELL編程

關於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 $File
20.done
21.echo "直接指定循環內容"
22.for i in f1 f2 f3 ;do
23.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))
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

Copyright © Linux教程網 All Rights Reserved