LINUX.IE, website of the Irish Linux Users' Group
Tux rules!

   
Home
New Users
Articles
Download
Projects
Community
Vendors

  Print Version
Email to...
 
Archives:


planetILUG

Recent News

News Archive


Join the
ILUG
on FaceBook


Join the
ILUG
on LinkedIn


Join the
ILUG SETI
Group



















 
 :: Mailing Lists

[ILUG] Bash using locally scoped vars inside while loop.

[ILUG] Bash using locally scoped vars inside while loop.

Kevin O' Riordan kor at compsoc.com
Tue Dec 3 15:21:03 GMT 2002


Hi folks,

when I use a while loop to read piped input, bash seems to use locally
scoped variables instead of assigning to global variables in that
script.  So far I've only seen this when I pipe data to a while loop.

I've put together a script that should explain this a lot better than
I'm doing.  Basically I'm wondering if I'm seeing a feature, a bug, or
what.  I'm searching thru the bash bug archives at the mo', and just
wondering if anyone else has come across this before.

I'm using bash 2.04.21 here.

cheers
-kev


########################################################################

#!/bin/bash

some_var="InitString"     # Initialize some_var.

echo ""

echo "while:"
echo "  BEFORE: $some_var"  # some_var before while.
i=0
while [ $i -lt 3 ]; do
    some_var="$some_var $i" # Assign to some_var inside while.
    echo "    in while: $some_var"
    i=$((i+1))
done
echo "  AFTER: $some_var"   # some_var has been changed, as expected.

echo ""

some_var="InitString"
echo "pipe to while:"
echo "  BEFORE: $some_var"      # some_var before pipe to while.
seq 1 3 | while read i; do
    some_var="$some_var $i"     # Assign to some_var ...
    echo "    in while: $some_var"  # ... show that some_var is changed.
done
echo "  AFTER: $some_var"       # Why is some_var unchanged here ?

echo ""

########################################################################

-- 
    The majority of the stupid is invincible and guaranteed for
    all time.  The terror of their tyranny, however, is alleviated
    by their lack of consistency.
        - Albert Einstein



More information about the ILUG mailing list
Read this without the formatting.
                                                                                                    

 

Hosted by HEAnet


Maintained by the ILUG website team. The aim of Linux.ie is to support and help commercial and private users of Linux in Ireland. You can display ILUG news in your own webpages, read backend information to find out how. Networking services kindly provided by HEAnet, server kindly donated by Dell. Linux is a trademark of Linus Torvalds, used with permission. No penguins were harmed in the production or maintenance of this highly praised website. Looking for the Indian Linux Users' Group? Try here. If you've read all this and aren't a lawyer: you should be!
RSS Version
Powered by Dell