Skeleton Bow
Skeleton Bow

Reputation: 529

Repeat bash command for n seconds

I've seen a lot of methods to repeat a bash command once every n seconds, but none to repeat a command for n seconds.

Is there a way to repeat a command for n seconds? So if my command takes one second to execute, it'll run ten times. If it takes two seconds, it'll run five times.

If it takes seven seconds, it would execute two times (and no more), or perhaps it would exit the script.

Right now I'm doing it by looking at the amount of time it takes for my script to execute once, and then calculating how many times I need to repeat it for it to execute for n seconds. However, this is slightly unreliable as I've found that the time required to run the script deviates a bit.

Upvotes: 0

Views: 588

Answers (2)

Gordon Davisson
Gordon Davisson

Reputation: 126078

timetorun=30    # In seconds
stoptime=$((timetorun + $(date +%s)))
while [ $(date +%s) -lt $stoptime ]; do
    something
done

Note that this will keep running the command until timetorun seconds have passed, so generally it'll actually run longer than that. For an extreme example, if timetorun is 30 seconds and the program takes 29 seconds, it'll run twice (and hence take 58 seconds).

Upvotes: 4

Chen A.
Chen A.

Reputation: 11338

You can use this if you know how many times you want it to be executed

num_iter = 15
while [ num_iter > 0 ]
do
    sh script.sh
    sleep 2
    let "num_iter--"
done

Or use watch -n to repeat a command every n seconds. Then you wrap the watch function and kill it after specific amount of time

Upvotes: 0

Related Questions