Linux读取循环时

时间:2013-10-04 13:50:53

标签: linux bash loops

我有以下脚本:

#!/bin/bash

function doPing () {
    pings=0

    #cat /home/scripts/test.txt | while read server ; do
    #while [ $pings -le 3 ] ; do
        echo success1 $pings
        if [ 1 -eq 1 ]; then {
            pings=$(expr $pings + 1)
            echo success- $pings
        } else if [ 1 -eq 2 ]; then {
            pings=$(expr $pings + 1)
            echo not
        } else {
            pings=$(expr $pings + 1)
            echo known
        } fi
        fi

        echo success3 $pings
    done

    echo -e "\nSuccessfully pinged $pings.\n"
}

doPing

test.txt包含几行服务器名称,实际上并不重要。

我的问题是,当我取消注释行#while ...时,我得到:

success1 0
success- 1
success3 1
success1 1
success- 2
success3 2
success1 2
success- 3
success3 3
success1 3
success- 4
success3 4
success1 4
success- 5
success3 5

Successfully pinged 0.

但是当我取消注释行#cat ...时,我得到:

success1 0
success- 1
success3 1
success1 1
success- 2
success3 2
success1 2
success- 3
success3 3
success1 3
success- 4
success3 4

Successfully pinged 4.

我怎样才能使#while输出为某个数字,如#cat ...,而不是零?请帮忙。感谢。

2 个答案:

答案 0 :(得分:2)

问题是管道创建了一个子shell,并且对子shell中的变量的更改不会传播到父级。

有关详细信息,请参阅this explanation about variables in pipelines

答案 1 :(得分:0)

这就是我所做的:

...
while read value ; do
...
done < /home/scripts/test.txt
...

...虽然我不知道-r之后read的含义。