Joy
Joy

Reputation: 23

Bash looping to run a command N times every second

I am trying to write a code so that a command repeats N(say 10) times every second in bash shell script. I am having problem in making the loop wait for the fraction of second left after sending the 1st 10 commands. I am using while loop to start the loop:

while [ $SECONDS -lt $((SECONDS+$time)) ]; do

for the number of commands I am using a for loop:

for i in $(seq 1 10); do echo 'Hello!'; done

Upvotes: 2

Views: 1514

Answers (1)

that other guy
that other guy

Reputation: 123460

You can start a sleep in the background and wait for it:

sleep 1 &
pid=$!

for i in $(seq 1 10); do echo 'Hello!'; done

wait "$pid"

This ensures that the wait will only wait for the remainder of the second, regardless of how long the for loop takes. (If it takes longer than 1 second, wait finishes immediately).

Upvotes: 4

Related Questions