首页 > 解决方案 > 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

标签: bash

解决方案


当到达输入文件的末尾时,您不会得到特殊值;而是read以非零退出状态退出,从而终止循环。例如:

count=0
total=0
while read -r num; do
    count=$((count + 1))
    total=$((total + num))
done

avg=$((total / count))

推荐阅读