bash - 如何将计算结果添加到变量中
问题描述
标准输入是
1\n2\n3
我试图将每个数字提高到 3 的幂,然后将它们的总和添加到 $count。
我正在尝试运行什么
xargs -I %var sh -c 'math stuff and increasing $count here???'
解决方案
如果所有数字都是整数,那么:
#!/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
一般不适用于数学计算。上面的代码是一个小计算的演示。
推荐阅读
- javascript - cy.reload() 无法在 Jenkins 上使用 Cypress 超时
- java - eclipse 上的 SonarLint:无法启动独立的 SonarLint 引擎
- jquery - 如何在提交没有特定库的表单时验证选择元素?
- java - 我制作了一个应用程序,如果您单击一个按钮,音频将播放,如果您单击两次,它将停止,但停止功能仅工作一次
- github-actions - 如何处理 GitHub Actions 在 7 天后删除其缓存
- logging - Azure ADF 管道复制数据日志文件未触发第二个管道的“已创建 Blob”触发器
- d3.js - d3js 移动节点旁边的标签
- powershell - Invoke-WUJob 什么都不做
- reactjs - 我应该保护构建的 NextJS 应用程序的哪些部分?
- c# - Automapper 包含父类的所有属性