bash:如何从读取命令中总结间隔数?

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

例如:

#!/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

所以,假设我们在执行代码时输入了 4 个数字,让我们输入 11 22 33 44.4,然后输入 enter,之后我们得到 853.6 作为结果,如果我'我没看错。

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

我从那长长的列表中选择了 ,因为这是我喜欢的列表:

#!/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

从现在开始,您可以使用 ${result} 做任何您需要做的事情。如果你需要用实数做除法,是你的朋友。

其中最棘手的部分是您在 done < <(...) 中看到的 process substitution 能够在 while 循环中设置变量,否则将是子 shell,并且让结果在循环外可用。