Shell编程之for循环语句

2019-12-20  本文已影响0人  你好树洞先生

Shell编程之for循环语句:

1.for循环基础语法:

for 变量名 in [ 取值列表 ]

do

    循环体

done

注意:for 循环按照空格,进行输出。

==========================================

2.for循环基本使用示例:

#取值列表有多种取值方式,可以直接读取in 后面的值,

默认以空格做分隔。

[root@test shell]# cat for-1.sh

#!/bin/bash

for var in file1 file2 file3

do

    echo the is $var

done

=========================================

3.for循环基本使用示例,从变量中取值

#!/bin/bash

list="file1 file2 file3"

for i in $list

do

  echo var is $i

done

[root@test shell]# sh for-2.sh

var is file1

var is file2

var is file3

=========================================

4.for循环基本使用示例,C语言风格的for

#语法格式

for ((i=0;i<10;i++))

do

  commands

done

例子1:单个变量,输出1到10之间的数字

[root@test shell]# cat for-3.sh

#!/bin/bash

for (( i=1;i<=10;i++))

do

    echo num is $i

done

[root@test shell]# cat for-4.sh

#!/bin/bash

a=10

b=1

for (( a>=1;b<=10; ))

do

  echo $a $b

  let a--

  let b++

done

========================================

例子2:多个变量,同时输出1-9的升序和降序

#解法1:

#!/bin/bash

for (( a=1,b=9;a<10;a++,b-- ))

do

    echo num is $a $b

done

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

#解法2:

#!/bin/bash

a=0

b=10

for i in {1..9}

do

  let a++;

  let b--;

  echo num is $a - $b

done

=============================================

上一篇下一篇

猜你喜欢

热点阅读