Very silly bash scripting question

Replicon

Member
Apr 23, 2002
152
0
71
I may be on crack here, but am I missing something about variable scoping here? Observe this simple script:

BOOBOO="blah"

echo $BOOBOO

ls | while read LINE; do
BOOBOO="moo"
echo $BOOBOO
done

echo "Final: $BOOBOO"

The 'ls' is just my excuse to get some kind of multiline input. Anyway, one would expect the global variable $BOOBOO to be changed to "moo" at the end, but instead, it remains "blah" (yet "moo" gets echoed for each line output by ls). I think this has to do with the while loop being part of the child process for ls, which makes sense (since if i take off the "ls |" and call it from the command line with "ls | script", it works fine).

I DO NOT want to have to do this (that is, I want to call ls from within the script). How do I do this without messing up the variables? I was thinking:

LS=`ls -1`

but that still stores it as ONE line, and I really want it as several.

Thanks
 

n0cmonkey

Elite Member
Jun 10, 2001
42,936
1
0
BOOBOO="blah"

echo $BOOBOO

ls | while read LINE; do
BOOBOO="moo"
echo $BOOBOO
done

echo "Final: $BOOBOO"

$BOOBOO is only set to "moo" within that while statement. I think. Maybe...

BOOBOO="blah"

echo $BOOBOO

ls | while read LINE; do
BOOBOO="moo"
echo $BOOBOO
done
BOOBOO="quack"
echo "Final: $BOOBOO"

This returns "Final: quack".
 

Replicon

Member
Apr 23, 2002
152
0
71
Originally posted by: Nothinman
If you want the variable to propogate you need to 'export' it.

Unfortunately, exporting doesn't seem to work (unless I'm doing something wrong). When you create a child process, it inherits your environment, but I don't think it actually edits that environment... I am trying to export stuff from within the loop (which is part of the child process because of the ls).

Note that if I take OFF the ls, and just read lines from the keyboard, then it's fine, because no child process is spawned from the script, and so no memory space is copied (so it's not because of the while loop).