Find the answer to your Linux question:
Results 1 to 3 of 3
Hi I'm trying to write a shell script using while read loop. The part that bothers me is this: Code: #!/bin/sh n=0 echo abc | while read line ; do ...
  1. #1
    Just Joined! phosphide's Avatar
    Join Date
    Oct 2007
    Location
    Kalisz, Poland
    Posts
    5

    Bash - global variable?

    Hi

    I'm trying to write a shell script using while read loop. The part that bothers me is this:
    Code:
    #!/bin/sh
    n=0
    echo abc | while read line ; do
    	n=$[n + 1]
    	echo $n
    done
    echo $n
    When executed, it gives output as follows:
    Code:
    1
    0
    - the value of n outside the loop doesn't change. What should I do to make that variable global?

    Thanks,
    phosphide

  2. #2
    Linux Newbie
    Join Date
    Sep 2004
    Location
    UK
    Posts
    160
    Code:
    #!/bin/sh
    n=0
    while read line 
    do
        n=$((n + 1))
        echo "In loop $n"
    done << MY_EOF
    `ls`
    MY_EOF
    
    echo "at end $n"
    replace `ls` with static text or whatever you need
    In a world without walls and fences, who needs Windows and Gates?

  3. #3
    Just Joined! phosphide's Avatar
    Join Date
    Oct 2007
    Location
    Kalisz, Poland
    Posts
    5
    Works perfectly, thank you!

Posting Permissions

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