Thursday, October 6, 2022

[SOLVED] Bash, how to calculate total from loop output

Issue

Please assist on that matter, I am trying to get a total number from loop that outputs 4 numbers as shown below:

#!/bin/bash
Bank=4
for ((out=1; out<=$Bank; out++)) do
        echo $out
done

I am getting output that looks like that:

1
2
3
4

How can I calculate 1+2+3+4 and get that calculated output 10 instead of 1 2 3 4? Originally variables 1 2 3 4 will be different like 585 430 170 64, can't figure out where to put | bc -l. Thanks!


Solution

where to put | bc -l

After the loop.

for ....
  ...
done | paste -sd+ | bc -l


Answered By - KamilCuk
Answer Checked By - Katrina (WPSolving Volunteer)