1

I have the following script:

#!/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 contains a few lines of server names, it does not matter actually.

My problem is that when I uncomment the line #while ..., I get:

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.

but when I uncomment the line #cat ..., I get:

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.

How can I make it so that the #while output will be some number pinged, like #cat ..., not zero? Please help. Thanks.

4

2 回答 2

2

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

有关更多信息,请阅读有关管道中变量的说明

于 2013-10-04T15:20:20.950 回答
0

这就是我所做的:

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

……虽然我不知道-r之后是什么意思read

于 2013-10-05T05:19:01.313 回答