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.

1
  • 1
    This is knit-picky (and not your problem), but you may want to adjust #!/bin/bash to be #!/usr/bin/env bash. That's more portable to other systems as it uses bash that's specified by the environmental vars. As far as the issue, I bet someone will beat me to an answer - but I am looking at it locally now. Commented Oct 4, 2013 at 14:10

2 Answers 2

2

The problem is that the pipe creates a subshell and changes to a variable in a subshell does not propagate to the parent.

For more information read this explanation about variables in pipelines.

Sign up to request clarification or add additional context in comments.

1 Comment

...and the solution is simple: remove the useless use of cat! Don't use a pipeline, use while ... done </home/scripts/test.txt.
0

This is what I did:

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

… although I do not know what -r means after read.

1 Comment

Yes, but what is the practical implication of this, that is what I do not get yet. Can it be that file then looks as one big line, even if in reality has more then one line? Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.