Linux基础------Shell中的循环

     

Linux基础------Shell中的循环


  Linux shell编程中也存在着循环。循环分为两种:一种是固定循环,另一种是不定循环。所谓固定循环和不定循环的定义是指在循环之前有没有定义好循环的次数。

例如:for循环,给定循环最大的次数,这就是固定循环。例如:while循环,只有满足指定的条件,循环才继续,它没有预先定义好的次数。

        shell当中的循环命令有for,while和until。

 一. for循环

       命令的基本格式:

       for var in list

       do

             your code

       done    

       list参数,是指的循环中的一系列值。每一次循环,程序都会将list中的一个值赋给var变量。举个例子:

#!/bin/bash

for test in a b c d
do
    echo $test
done
输出:a b c d


      稍微复杂一点的例子,for也可以从命令中读取值,

先保存一个文本文件,命名为test,里面存放的信息如下:

test1 test2

test3

test4


#!/bin/bash

file="test"
for line in `cat $file`
do
   echo "This line of file is : $line"
done
输出:

This line of file is:test1

This line of file is:test2

This line of file is:test3

This line of file is:test4


特别强调的是上面``,不是单引号' ',它是键盘左上角的反引号。在linux里面,反引号之间的是可执行的命令。

关于for循环,里面还有一个很重要的知识:IFS

IFS是一种被称为内部字段分割符的环境变量(internal field separator)     。IFS定义了shell中用作字段分割的一系列字符。默认的字符为3种:空格,制表符,换行符。

shell在数据当中看到上述其中的任意一个字符,都会假定是开始了一个新的数据段,所以上面的脚本输出了4行数据。下面只要改一下IFS,输出的内容就会发生改变:

#!/bin/bash

file="test"
IFS=$'\n'
for line in `cat $file`
do
   echo "This line of file is : $line"
done
输出:

This line of file is:test1 test2

This line of file is:test3

This line of file is:test4

在for循环当中我们可能需要改一下IFS,但是在其他的地方我们需要默认的IFS,所以在程序中,应该这样写:

IFS.OLD=$IFS
IFS=$'\n'
your code
IFS=IFS.OLD

二. C风格的for循环

使用方法:

for (( variable assignment; condition; iteration process ))   ------>注意空格

do

  your code

done


下面是一个例子:

#!bin/bash

for (( i=1; i <=3; i++))
do
    echo "Number is $i"
done

输出:

Number is 1

Number is 2

Number is 3


三. while循环

使用方法:

while test command

do

    your code

done

while允许定义多个测试命令(test command)。只有最后一个测试命令才来用来决定什么时候退出循环。例子如下:

#!/bin/bash

var1=10
while echo $var1
          [ $var1 -ge 0 ]
do
    echo "This is inside the loop"
    var1=$[ $var1 - 1 ]
done
输出:

10

This is inside the loop

9

This is inside the loop

8

This is inside the loop

7

This is inside the loop

6

This is inside the loop

5

This is inside the loop

4

This is inside the loop

3

This is inside the loop

2

This is inside the loop

1

This is inside the loop

-1


四. until循环

使用方法:

until test command

do

    your code

done


#!/bin/bash

until [ "$yn" != "y" -a "$yn" != "Y" ]
do
read -p "Please input y/Y to stop this program: " yn
done
echo "Loop End"

until和while循环正好相反,当满足条件时,循环会自动退出。


四. 循环控制

break:跳出循环,默认的是跳出当前循环,如果break n,n就是指定的循环层数。例如break 2就是当前循环外的另一层。

continue:执行到contune时,跳出其他的linux命令,直接进行下一个循环。continue n与break n类型,也是指定循环的层数。




猜你喜欢

转载自blog.csdn.net/u010127879/article/details/21888859