Find the answer to your Linux question:
Results 1 to 3 of 3
Hi all, I am new to bash programming and am stuck with a seemingly simple problem. Here is my script: #!/bin/bash X=0 cat test.sh | while read LINE do echo ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1
    Just Joined!
    Join Date
    Nov 2006
    Posts
    1

    while loop using cat <file> | while read LINE


    Hi all,
    I am new to bash programming and am stuck with a seemingly simple problem. Here is my script:

    #!/bin/bash
    X=0
    cat test.sh | while read LINE
    do
    echo $X
    X=`expr ${X} + 1`
    done
    echo "Issue X="${X}

    B=0
    while [ $B -le 20 ]
    do
    echo $B
    B=$((B+1))
    done
    echo "No issue B="$B


    The issue is that in the first loop X looses its value once it comes out of the loop. However in the second loop, B does not loose its value.

    Can someone tell me what am I doing wrong?

    paudhe

  2. #2
    Linux Guru Cabhan's Avatar
    Join Date
    Jan 2005
    Location
    Seattle, WA, USA
    Posts
    3,252
    That is a strange issue, but as usual, the ABS talks about this:

    http://www.tldp.org/LDP/abs/html/int...ml#READPIPEREF

    As you know, a script runs inside of a subshell. From what I can figure out, piping cat's output into the loop opens up a new subshell: $X is set within the subshell, but once we exit that pipe (by exiting the loop), we are back in the parent shell, where $X is unset.

    So it all has to do with you piping cat into the loop.

  3. #3
    Linux Enthusiast
    Join Date
    Aug 2006
    Posts
    631
    Quote Originally Posted by Cabhan
    That is a strange issue, but as usual, the ABS talks about this:

    http://www.tldp.org/LDP/abs/html/int...ml#READPIPEREF

    As you know, a script runs inside of a subshell. From what I can figure out, piping cat's output into the loop opens up a new subshell: $X is set within the subshell, but once we exit that pipe (by exiting the loop), we are back in the parent shell, where $X is unset.

    So it all has to do with you piping cat into the loop.
    So don't cat the file but redirect it:
    Code:
    #!/bin/bash
    
    X=0
    while read LINE
    do
      echo $X
      X=`expr ${X} + 1`
    done < test.sh
    echo "Issue X="${X}
    
    B=0
    while [ $B -le 20 ]
    do
      echo $B
      B=$((B+1))
    done
    echo "No issue B="$B
    Regards

  4. $spacer_open
    $spacer_close

Posting Permissions

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