Find the answer to your Linux question:
Results 1 to 3 of 3
This really has me stumped: First script gives the expected output, however when I change the nested loop from a "for" loop to a "while" loop, observe what happens to ...
  1. #1
    Just Joined!
    Join Date
    Jan 2007
    Posts
    19

    while loop read mystery

    This really has me stumped: First script gives the expected output, however when I change the nested loop from a "for" loop to a "while" loop, observe what happens to the count output:

    #!/bin/bash

    count=1

    for line in one two threeXfour fiveXsix seven eight
    do

    echo "$line" | grep "X" > /dev/null
    if [ $? == 0 ]
    then
    var=`echo "$line" | sed 's/X/\n/g'`
    for line2 in $var
    do
    echo $count
    let count=count+1
    echo $line2
    done
    else
    echo $count
    let count=count+1
    echo $line
    fi

    done

    #output:

    1
    one
    2
    two
    3
    three
    4
    four
    5
    five
    6
    six
    7
    seven
    8
    eight



    When reading from a "while" loop, output is as follows:


    #!/bin/bash

    count=1

    for line in one two threeXfour fiveXsix seven eight
    do

    echo "$line" | grep "X" > /dev/null
    if [ $? == 0 ]
    then
    echo "$line" | sed 's/X/\n/g' | \
    while read line2
    do
    echo $count" " > /dev/stderr
    let count=count+1
    echo $line2
    done
    else
    echo $count" " > /dev/stderr
    let count=count+1
    echo $line
    fi

    done

    #output

    1
    one
    2
    two
    3
    three
    4
    four
    3
    five
    4
    six
    3
    seven
    4
    eight


    Anyone know why?

  2. #2
    Linux User
    Join Date
    Nov 2009
    Location
    France
    Posts
    292
    Piping to a while loop makes the loop to run in a sub-shell. There was a discussion about it on this forum recently, I can't trace it back. You can get more info here :
    Variable Scope in Bash (NuclearDonkey.net)
    0 + 1 = 1 != 2 <> 3 != 4 ...
    Until the camel can pass though the eye of the needle.

  3. #3
    Just Joined!
    Join Date
    Jan 2007
    Posts
    19
    aaahhh, thanks.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...