18

I know how to execute multiple commands at same time but now what I need is to run the same command multiple times with some time delay between the command execution.

Requirements

  • I don't want to use a script for this
  • A single one line command to accomplish this
  • Needs to run on Linux
  • Need to control the number of times the command will run
2
  • I'm not sure I understand the question. Is this sufficient? echo 'hello'; sleep 3; echo 'goodbye' Nov 22, 2013 at 6:29
  • that is ok but I want the execute the same command for more and I would not like to use echo 'hello'; sleep 1; again same command.Basically, I would like to control the number of times that I would like to repeat the command
    – Özzesh
    Nov 22, 2013 at 6:37

3 Answers 3

26

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
2
  • 1
    Why starting a subshell? Why not just for i in {1..5}?
    – Bernhard
    Nov 22, 2013 at 11:42
  • @Bernhard - thanks, apparently I like using seq too much, I've added a section showing brace expansions.
    – slm
    Nov 22, 2013 at 12:00
19

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).

1
6

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;
1
  • 2
    Try not to use the back ticks, they're deprecated. Use $(..) instead.
    – slm
    Nov 22, 2013 at 6:41

Not the answer you're looking for? Browse other questions tagged or ask your own question.