LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   working with variables- how? (https://www.linuxquestions.org/questions/linux-newbie-8/working-with-variables-how-648081/)

pdklinux79 06-09-2008 01:39 PM

working with variables- how?
 
hi i am working in bash.

few lines of code is :
1.num=1

2.grep '^ID' vdat.txt | while read line
3.do
4.field_3=$(echo "$line" | awk '{print $3}')
5.echo $field_3
6.array[$num]=$field_3
7.echo ${array[$num]}
8.num=`expr $num + 1`
9.done
10.echo $num

the value of num at line 10 is 1 even after manipulating it in the line 8 inside for loop.. lets say it is a for loop with i=1, i<=4 i++ and i manipulate the value of num inside the forloop.

how can get the value of num as 4 outside the loop?

im having problem as the num inside the loop becomes local and doesnt effact the global variable

am a newbie.. please help me.

Uncle_Theodore 06-09-2008 02:10 PM

Quote:

Originally Posted by pdklinux79 (Post 3179546)
hi i am working in bash.

few lines of code is :
1.num=1

2.grep '^ID' vdat.txt | while read line
3.do
4.field_3=$(echo "$line" | awk '{print $3}')
5.echo $field_3
6.array[$num]=$field_3
7.echo ${array[$num]}
8.num=`expr $num + 1`
9.done
10.echo $num

the value of num at line 10 is 1 even after manipulating it in the line 8 inside for loop.. lets say it is a for loop with i=1, i<=4 i++ and i manipulate the value of num inside the forloop.

how can get the value of num as 4 outside the loop?

im having problem as the num inside the loop becomes local and doesnt effact the global variable

am a newbie.. please help me.

OK, the problem is that when you use a pipe, bash forks out a subshell which performs your while loop. Variables, including your $num are specific to that subshell and when the loop is finished, you see the original $num that has never been modified.

On a side note, this line num=`expr $num + 1` seems strange. Do you mean something like num=$((num+1)) ?

pdklinux79 06-09-2008 02:27 PM

yes.. it is num= num+1..

so how do i get the effect i want?is there any way?

Uncle_Theodore 06-09-2008 02:35 PM

Quote:

Originally Posted by pdklinux79 (Post 3179592)
yes.. it is num= num+1..

so how do i get the effect i want?is there any way?

Well, grep the file without a pipe. Something like this

Code:

1.num=1

2.while read line
3.do
4.field_3=$(echo "$line" | awk '{print $3}')
5.echo $field_3
6.array[$num]=$field_3
7.echo ${array[$num]}
8.num=$((num+1))
9.done < <(grep '^ID' vdat.txt)
10.echo $num

should do it.

pdklinux79 06-09-2008 02:51 PM

Thank you Uncle Theodre so much.. it is working..

CanOfPoke 06-10-2008 04:50 AM

I had same problem it all works fine now though.


All times are GMT -5. The time now is 11:05 AM.