bash - Bash while 循环直到 EOF
问题描述
我需要编写一个程序来计算整数除法的算术平均值和方差,但我现在不知道要输入多少个数字。示例输入:
5
4
1
5
2
6
示例输出:
3
8
现在,当我输入x
而不是数字时,循环结束,但是这些数字是从文件中读取的,所以我认为它应该是这样的:
while read -r num; do
if [[ "$num" -eq EOF ]]; then #that condition is my question, what should be inside [[]]?
break
fi
else
#do sth
done
#the rest of the program
解决方案
当到达输入文件的末尾时,您不会得到特殊值;而是read
以非零退出状态退出,从而终止循环。例如:
count=0
total=0
while read -r num; do
count=$((count + 1))
total=$((total + num))
done
avg=$((total / count))
推荐阅读
- php - 如何使用 AND 和 OR 条件创建 php 标签搜索字段?
- python - 匹配两个二维数组的行并使用 numpy 获取行索引映射
- java - 如何使用 LocalDateTime java 检查最小和最大时间,即最小 10:00 和最大时间 10:30
- node.js - 我如何测试 node.js 模板渲染在开玩笑
- serial-port - 强制接口上的信号 (RS-232)
- scala - 返回另一个函数的scala递归函数
- pandas - 如何在 pandas 中使用 apply 函数,同时将索引映射到两个不同的数据帧?
- web-component - 发布自定义元素、命名约定、最佳实践?
- python - 没有错误,但是当我运行它时,它显示一个白屏
- python - ArrayField 没有更新?