I have a while loop in a bash script which should do something different at the beginning and at every 5 second interval. Any previous loop is allowed to complete. The 5s interval is indicated by the do_different global variable set by the heartbeat function. An additional complication is that a normal while loop completes in an unknown amount of time (simplified with RANDOM in below script).Using cron is not an option, neither is timing the random process.I already unsuccessfully tried using a pipe as well as process substitution.The whole script may be re-factored.#!/bin/bashfunction heartbeat {    do_different=true    while sleep 5s    do        do_different=true    done}heartbeat &while truedo    if $do_different    then        echo 'Something different'        do_different=false        i=0    else        # process of random duration; not important        r=$(( 1 + RANDOM % 3 ))        sleep ${r}s        i=$((i + r))        echo $i    fidone
How to influence a bash while loop with a timed global variable?
bash;shell script;pipe;sleep
Here is the code I am running now, based on airfishey's answer with some corrections.#!/bin/basht_lastdue=$(date --date='5seconds ago' +%s)while truedo    t_now=$(date +%s)    t_elapsed=$((t_now - t_lastdue))    if [ $t_elapsed -ge 5 ]    then        echo 'Something different'        t_lastdue=$((t_lastdue + 5))        i=0    else        # process of random duration; not important        r=$(( 1 + RANDOM % 3 ))        sleep ${r}s        i=$((i + r))        echo $i    fidone