Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

scope of arrays question

Status
Not open for further replies.

awingnut

Programmer
Feb 24, 2003
759
US
I am having a problem with the scope of an array. I have a 'grep <blah blah> | while read line ; do' loop that builds and array and before the 'done' the array contains exactly what I want. After the 'done' the array is zeroed. I don't understand why the array does not survive the scope of this 'do'. In any case, how do I change the scope? TIA.
 

Linux? then this is how bash shell behaves. [thumbsdown]





----------------------------------------------------------------------------
The person who says it can't be done should not interrupt the person doing it. -- Chinese proverb
 
Does it work if you define and export the array variable before the loop?
 
Hi

This is a real PITA. I searched for workarounds and alternatives, for a long time but I found only one solution. Probably the ugliest possible :

Code:
i=0
eval `seq 5 7 | while read num; do echo arr[i++]=$num; done`
echo ${arr[*]}

Feherke.
 
Thanks. Export does not work either. Anyway I got the answer so I'll have to program around it.
 
Hi

Now I found out abit more. If you pipe something into [tt]while[/tt], then it will act as a new process and the values set inside will not be available after. But [tt]while[/tt] can get input through [tt]<[/tt] redirection, in which case everything set inside will remain available.

Code:
[gray]# no $val after this[/gray]
date [green]|[/green] [navy]while[/navy] read str; [navy]do[/navy] val=$str; [navy]done[/navy]
[gray]# $val will have the date after this[/gray]
date [green]>[/green] /tmp/temp; [navy]while[/navy] read str; [navy]do[/navy] val=$str; [navy]done[/navy] [green]<[/green] /tmp/temp

So you must use a temporary file, but I think sometime is not so big impediment.

Feherke.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top