1

Why does ...

sum=0; for i in 1 2 3 4; do echo "$i" | sum=$((sum+i)); done; echo $sum

... work as expected in zsh but not in bash? Perhaps because of bash not supporting floating point arithmetic? I also tried ...

sum=0; for i in 1 2 3 4; do echo "$i" | awk '{sum+=$1}'; done; echo $sum

... but that doesn't work in neither (this is on macOS 10.14.2). I found several related questions (such as this or this) but this question still remained.

Marius Hofert
  • 6,546
  • 10
  • 48
  • 102
  • 1
    See https://unix.stackexchange.com/questions/40786/how-to-do-integer-float-calculations-in-bash-or-other-languages-frameworks – Wiktor Stribiżew Jan 20 '19 at 20:50
  • 1
    As [shellcheck](https://www.shellcheck.net) points out, the reason why the first one does not work is because the variable was [modified in a subshell](https://github.com/koalaman/shellcheck/wiki/SC2031). See [this question](https://stackoverflow.com/questions/16854280/a-variable-modified-inside-a-while-loop-is-not-remembered) for a more common symptom of the same problem – that other guy Jan 20 '19 at 21:21

1 Answers1

4

there is a wrong "|"

sum=0; for i in 1 2 3 4; do echo "$i" ; sum=$((sum+i)); done; echo $sum  
1
2
3
4
10

The second example does not work as you are invoking awk every time the loop is repeated so the value of sum is not stored.

matzeri
  • 8,062
  • 2
  • 15
  • 16
  • What if the variable 'i' is not known (like in the second example)? How would you add to `sum` then? – Marius Hofert Jan 20 '19 at 21:04
  • ... that's why I 'piped' (this is only a MWE and the `i` is actually an output from a previous command that is executed) – Marius Hofert Jan 20 '19 at 21:12
  • piped to what ? The assignment is right without the echo. – matzeri Jan 20 '19 at 21:14
  • 2
    @MariusHofert Just put it in a variable first, e.g. `i=$(your long command)`. – that other guy Jan 20 '19 at 21:18
  • @MariusHofert I think you've left too much out of your MWE. In the first example, the value being `echo`ed is never read and has no effect on the summation. In the second example, `sum` is an `awk` variable, not a shell variable, and since a new `awk` is run every time it's a completely different variable each time through the loop. You need to include more of what you're actually trying to do. – Gordon Davisson Jan 20 '19 at 21:19
  • ... right, thanks. I just found the solution by assigning the output (here: simplified) to a variable and then updating the sum. Thanks a lot. – Marius Hofert Jan 20 '19 at 21:25