Search code examples
printfechouser-inputcalc

bash: how to sum up spaced number from read command?


for example:

#!/bin/bash

printf '%s' "write 4 numbers separated by spaces:"

read -r var

# suppose to print sum of calculated numbers, in this case I want to calculate like this:
# ((1n*2n)+(3n*4n))/2 <----divided by (total item/2)

exit 0

so, lets say we put 4 numbers when we execute the code, lets put 11 22 33 44.4, and then enter, after that we got 853.6 as the result if i'm not mistaken.


Solution

  • is lacking built-in support for calculations with real numbers but there are lots of options.

    From that long list I picked since it's the one I'm comfortable with:

    #!/bin/bash
    
    wanted_numbers=4
    read -p "write ${wanted_numbers} numbers separated by spaces: " line
    #echo "debug: line >$line<" >&2
    
    result=0
    numbers=0
    
    while read var
    do
        #echo "debug: got >$var<" >&2
        result=$(bc <<< "${result}+${var}")
        numbers=$((numbers + 1))
    done < <(tr ' ' '\n' <<< $line)
    
    if [[ $numbers != $wanted_numbers ]]; then
        echo "I asked for ${wanted_numbers} numbers and got ${numbers}. Try again..." >&2
        exit 1
    fi
    
    echo $result
    

    From here on you can do whatever you need to do with ${result}. If you need to do division with real numbers, is your friend.

    The trickiest part in this is the process substitution that you see in done < <(...) to be able to set variables in the while loop, in what would otherwise be a subshell, and have the result available outside the loop.