I have a bash script that for each file in a set, greps each line in the file for a string. Then it splits the line on commas, converts the 7th element to a float, and increments a running total by that value.
It looks like this:
for filename in data*.CSV; do
echo $filename
ACTUAL_COST=0
grep '040302010' $filename | while read -r line ; do
IFS=',' read -a array <<< "$line"
ACTUAL_COST=$(echo "$ACTUAL_COST + ${array[7]}" | bc)
echo $ACTUAL_COST
done
echo $ACTUAL_COST
done
But the problem I'm having is that this produces output like this:
53.4
72.2
109.1
0
The last value is always 0. After Googling a bit, I think this is because the while
loop is executing in a subshell, and so the outer variable isn't changed.
I understand that I probably need to execute the inner loop in a function.