首页 > 解决方案 > bash:如何总结读取命令中的间隔数?

问题描述

例如:

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

标签: printfechouser-inputcalc

解决方案


数计算的内置支持,但有很多选项

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

#!/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 < <(...),以便能够在while循环中设置变量,否则将是一个子shell,并在循环外提供结果。


推荐阅读