LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (http://www.linuxquestions.org/questions/linux-general-1/)
-   -   BASH: variables inside "while" loop are local ? (http://www.linuxquestions.org/questions/linux-general-1/bash-variables-inside-while-loop-are-local-939518/)

marozsas 04-12-2012 03:09 PM

BASH: variables inside "while" loop are local ?
 
Hi,

This is fine.No news here.
Code:

a=2; for i in $(seq 1 3) ; do echo a=$a; a=1; done; echo a=$a
a=2
a=1
a=1
a=1

But this is unexpected - at least for me! :)
Code:

a=2; seq 1 3 | while read f; do echo a=$a; a=1; done; echo a=$a
a=2
a=1
a=1
a=2

Looks like "a" is a global variable inside the while loop before the assignment, and a local variable after the assignment. At end, "a" still has the original value.

How can I use a global variable inside the "while" loop ? I want a behavior like the first one that use a "for" loop.

kbp 04-12-2012 07:17 PM

Whe you use a pipe to join commands, each command is run in a subshell.

marozsas 04-13-2012 03:25 PM

Hi kbp,

uhmm...so exporting variable "a" should work, but not.
Code:

export a; a=2; seq 1 3 | while read f; do echo a=$a; a=1; done; echo a=$a
a=2
a=1
a=1
a=2

Do you have a explanation ? Or better yet, a solution to this problem ? I mean, at end of "while" loop, how can I have access to variables that was set inside the loop ?


All times are GMT -5. The time now is 01:38 PM.