How to execute same command "X" multiple times with a time delay of some number of seconds?
You can use this one liner to do what you're asking:
$ cmd="..some command..."; for i in $(seq 5); do $cmd; sleep 1; done
Example
$ date
Fri Nov 22 01:37:43 EST 2013
$ cmd="echo"; for i in $(seq 5); do $cmd "count: $i"; sleep 1;done
count: 1
count: 2
count: 3
count: 4
count: 5
$ date
Fri Nov 22 01:37:51 EST 2013
You can adjust the sleep ...
to what ever delay you'd like between commands, and change cmd=...
to whatever command you want.
Brace expansions vs. seq cmd
You can also use brace expansions instead of the seq
command to generate ranges of values. This is a bit more performant since the brace expansions will run in the same shell as the for
loop. Using the subshell ($(seq ..)
) is a little less performant, since it's spawning a subshell within the confines of the shell that the for
loop is running.
Example
$ cmd="echo"; for i in {1..5}; do $cmd "count: $i"; sleep 1;done
count: 1
count: 2
count: 3
count: 4
count: 5
With zsh
:
repeat 10 {date; sleep 5}
That runs the commands (here date
as an example) with a 5 second sleep in between them.
If instead you want to run it every 5 second (and assuming the command takes less than 5 seconds to run):
typeset -F SECONDS=0; repeat 10 {date; ((n=5-SECONDS)); SECONDS=0; LC_ALL=C sleep $n}
(Assuming a sleep
implementation that supports fractionnal seconds).
This runs the date
command for 10 times with a 5 second delay. Change the 10 in seq 1 10
for the number of times you want, replace date
with the command you want and change the 5 in sleep 5
to change the delay time.
for d in $(seq 1 10); do date; sleep 5; done;