Quote:
Originally Posted by pdklinux79
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)) ?