shell (二) shell for循环

for循环

基本示例

for i in var1 var2 var2
do
    echo $i
done

for i in {1..100}
do
    echo $i
done

列表中复杂值,可以使用引号或者转义字符来约束

# 双引号
for i in var1 "var2 var2" var4 "var5 var6"
do
    echo $i
done

输出:
var1
var2 var2
var4
var5 var6


# 转义符
for var in var1 var2\'2 a\'b
do
    echo $var
done

输出:
var1
var2'2
a'b

for var in var1 "var2\'2 a\'b"
do
    echo $var
done

输出:
var1
var2\'2 a\'b

从变量中取值

list="a b c"
for i in $list
do
    echo $i
done
输出:a b c

从命令中取值

for i in `cat /etc/hosts`
do
    echo $i
done

输出:
##
#
Host
Database
#
#
localhost
is
used
to
configure

自定义分隔符

for循环,默认情况下以空格为分隔符,可以通过IFS来自定义分隔符

  • 以冒号为分隔符 IFS=:
  • 以冒号分号双引号为分割符 IFS=:;"
  • 以换行符为分隔符 IFS=$'\n'
IFS=$'\n'
for i in `cat /etc/hosts`
do
    echo $i
done

输出:
##
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting.  Do not change this entry.
##
127.0.0.1       localhost
255.255.255.255 broadcasthost
::1             localhost

C语言风格的for

for ((i=0; i<10; i++))
do
  echo $i
done

输出:
0
1
2
3
4
5
6
7
8
9

练习题

用for循环10次,输出两个数字之和
示例:
num is 1 9
num is 2 8
num is 3 7
num is 4 6
num is 5 5
num is 6 4
num is 7 3
num is 8 2

解:
# 第一种解法
for (( a=1, b=9; a<9; a++, b-- ))
do
   echo num is $a $b
done 

# 第二种解法
a=0
b=10
for i in  {1..9}
do
   let a++
   let b--
   echo num is $a $b
done 

# 如果需要求和

for (( a=1, b=9; a<9; a++, b-- ))
do 
   sum=$(( $a + $b ))
   echo num is $a + $b = $sum
done 

posted @ 2019-11-28 15:53  zelatan  阅读(563)  评论(0编辑  收藏  举报
AmazingCounters.com