Here is a shell script. Please extrapolate the controlled-environment random number generation subshell to the use of this in an asynchronous logging situation (I intend to use it for inotifywait output).
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
This produces output like this:
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
But it then hangs and does not exit. It is stuck in the outer loop, continually incrementing group:
$ echo $group
1336794
Clearly the inner loop has exited due to input having finished, and the incrementation of the variable went into hyperdrive.
How to exit the loop? Is there like a else clause of some sort that I can hack on to the inner for loop in order to break out of the outer loop, once the input has finished coming in?
Surely there must be a more robust method than doing timing in the outer loop to see if it went through too fast.
break n.... n you can specify the nesting/number of loops you wanna get out of .... (if check for the break 2 stmt.)break. Where would it go? The inner loop times itself out every second.