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
slm
  • 369,824
Özzesh
  • 3,669
  • I'm not sure I understand the question. Is this sufficient? echo 'hello'; sleep 3; echo 'goodbye' – ire_and_curses Nov 22 '13 at 06: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 '13 at 06:37

3 Answers3

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
slm
  • 369,824
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).

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;
zje
  • 2,311