这是一个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/