Here is the script i try to perform arithmetic operation in two variables .
git branch -r | while read brname ; do
REV_COMMITS=`git rev-list --count $brname`
echo "$brname has $REV_COMMITS"
(( TOTAL = TOTAL + REV_COMMITS ))
echo "in loop" $TOTAL
done
echo "total is " $TOTAL
Output:
In side the loop, i get correct value of variable TOTAL.
How to get correct TOTAL outside while loop ?
When you run shell commands in a pipe, they exist inside a different shell. This shell sums up the value perfectly and quits - leaving you in your original shell where the value was never changed.
Which end of the pipe is 'your' shell can vary from shell to shell. In KSH, you'd have gotten the total; I suspect you're running bash.
There's a few ways to deal with this and make it work in both.
Stuffing the entire program into the subshell with ( ) grouping braces:
git branch -r | (
while read something
do
...
done
echo "total is $total"
)
Here-doc:
while read something
do
...
done <<EOF
$(git branch -r)
EOF