How to timeout bash while loop in given seconds/minutes

This is simple but might be a bit more interesting.
If there is an elegant solution it will be very useful.

    #!/bin/bash
    while IFS= read -r line
    do
    echo "running"
    done< <(sleep 10)
    exit

The code above starts the loop with a 10 second timeout after which the loop terminates.
Obviously since nothing is read, there is nio cycling and the echo is not executed.

Is there a way to make the while loop cycle and continuously print the echo using the sleep command with some other wizardry fed in to the loop as currently done. ?
Or to alter the IFS variable declaration in a way that can effect that ?

I was thinking along the lines to replace sleep 10 with timed random data as in the script. The random data will loop the while loop but it needs be terminated by the sleep 10.

Sort of a
}> >(sleep10–Randomdata something)

Cannot think of a way to make this work or if it is possible.

I dont need any of the data fed in to the loop. I only need the loop to cycle for 10 seconds.

This can be very useful for timed menu selections after a certain timeout (user is finished fidling) the current selection is made effective.

Fine, I can solve this if I can generate a script that outputs random data for a period of time and then save in /usr/bin and call it in place of Sleep 10 above, but it would noce to do this with built in commands.

Look into timeout command

#!/bin/bash
while IFS= read -r line
do
   echo "running"
done

Run it as

timeout 10s /path/to/my/script

See:

1 Like

Thanks it has to be feeding the Procedure itself, but it seems this will work.
I googled it a lot and did not come across your Howto you linked.
Really dont know why.
Thanks.

#!/bin/bash
   
    p_test () {
    while IFS= read -r line
    do
    date
    done
}< <(timeout 2s cat /dev/urandom )

p_test

exit

Here is demo how i want to use it. Works like a charm !!!
Solves some nagging problems for me about processes that needs to be watchdogged ACCURATELY in a self contained way not from call.

So much better than self contained internal watchdogs that get inaccurate in busy programs and overshoots it’s time limit under stress or less powerful processor.

This makes the watchdog way more reliable.
I tried it on some of my embedded programs on small processors and all the preexisting watchdog issues disappeared. I jusr give timeout the highest priority and it is rock solid. Neat !

**Thanks Nixcraft. **
You are the ace !.. as usual.


Linux sysadmin blog - Linux/Unix Howtos and Tutorials - Linux bash shell scripting wiki