0

I use Ubuntu Server as you can see:

#uname -a
Linux grosella 3.13.0-48-generic #80-Ubuntu SMP Thu Mar 12 11:16:15 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux

Supose a data file like this (/tmp/data.txt):

1 AAAA
2 BBBB
3 CCCC
4 DDDD
5 EEEE
6 FFFF

Run the following Bash script:

typeset -i ACUM=0
typeset -a V=('')

cat /tmp/data.txt | \
while read LINEA ; do
  [ "x$LINEA" == "x" ] && break
  V=( $LINEA )
  VAL="${V[0]}"
  [ "x$VAL" == "x" ] && continue
  [[ $VAL =~ ^[0-9]+$ ]] || continue
  ((ACUM+=VAL))
  echo -e "VAL=$VAL\t\tACUM=$ACUM"
done

echo -e "\nFinal Result: $ACUM"

And here is the printed output:

VAL=1       ACUM=1
VAL=2       ACUM=3
VAL=3       ACUM=6
VAL=4       ACUM=10
VAL=5       ACUM=15
VAL=6       ACUM=21

Final Result: 0

Instead of 21, final result is 0. What is wrong?

abadjm
  • 156
  • 5

2 Answers2

3

When you pipe the data to your while loop that creates a subshell in which the while loop runs. The subshell cannot alter the environment variables of the parent, so the outer ACUM does not get changed.

Eric Renouf
  • 13,950
  • 3
  • 45
  • 67
2

Change your code from

cat /tmp/data.txt | \
while read LINEA ; do
  # ...
done

to

while read LINEA ; do
  # ...
done < /tmp/data.txt

to avoid two subshells with its own environment.

Cyrus
  • 84,225
  • 14
  • 89
  • 153