bash - 如果输入由内部 "while read"处理,我如何才能跳出 shell 脚本循环?

标签 bash shell unix

这是一个shell脚本。请将受控环境随机数生成子 shell 推断为在异步日志记录情况下使用它(我打算将它用于 inotifywait 输出)。

group=0
(
  for val in {1..10}; do 
    echo "$RANDOM/20000" | bc | xargs sleep # this waits 0, 1, or 2 seconds before each number is printed
    echo $val 
  done 
) | while true; do 
      while read -t 1 line; do 
        echo "read time=$group read=$line" 
      done
      ((group++))
    done

这会产生如下输出:

read time=1 read=1
read time=2 read=2
read time=2 read=3
read time=3 read=4
read time=3 read=5
read time=3 read=6
read time=4 read=7
read time=5 read=8
read time=5 read=9
read time=5 read=10

但是它随后挂起并且没有退出。它卡在外循环中,不断递增group:

$ echo $group 
1336794

很明显,由于输入已经完成,内部循环已经退出,并且变量的增量进入了超光速引擎。

如何退出循环?是否有某种类型的 else 子句,我可以破解内部 for 循环,以便在输入完成后 break 退出外部循环?

肯定有比在外循环中计时更可靠的方法,看看它是否通过得太快。

最佳答案

#!/bin/bash
mkfifo outputs
for val in {1..10}; do
    echo "$RANDOM/20000" | bc | xargs sleep
    echo $val 
done > outputs &
group=0
time=$(date +%s%N)
while read line; do
    ctime=$(date +%s%N)
    [ $(( $ctime - $time )) -gt 1000000000 ] && let group++
    echo "read time=$group read=$line"
    time=$ctime
done < outputs

关于bash - 如果输入由内部 "while read"处理,我如何才能跳出 shell 脚本循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16953540/

相关文章:

bash - 在 Bash shell 脚本中传播所有参数

bash - 显示文件的十六进制数

linux - 根据情况重新构建 shell 脚本

linux - grep 包含 "+"的变量

linux 文件和文件夹不继承父目录权限

bash - 如何在 unix 终端的唯一顺序列表(每行一个)中找到丢失的整数?

arrays - 如何在 bash 中回显数组中的所有值

linux - Bash 脚本 - 遍历关联数组列表的 "variable"变量名

linux - 如何在 linux-shell 中使用 `amp;` 和 `gt;` 命令?

bash - make -e 只从子shell退出