首页 > 解决方案 > 如何将计算结果添加到变量中

问题描述

标准输入是

1\n2\n3

我试图将每个数字提高到 3 的幂,然后将它们的总和添加到 $count。

我正在尝试运行什么

xargs -I %var sh -c 'math stuff and increasing $count here???'

标签: bash

解决方案


如果所有数字都是整数,那么:

#!/bin/bash

pow=3                           # raise inputs to the power of 3
count=0                         # whatever pre-defined value

[[ -t 0 ]] && echo "Input number and press enter key. Type Ctrl-D when you are done."
                                # show the message if stdin is console input

while IFS= read -r i; do        # read the input line by line
    (( sum += i ** pow ))       # accumulate the exponentiations
done
(( count += sum ))              # add to the $count
echo "count = $count"

调用上述脚本时,请尝试在标准输入中输入数字和 Ctrl+D。
请注意bash一般不适用于数学计算。上面的代码是一个小计算的演示。


推荐阅读