How to run a command every x interval of time in terminal?

Option #1:

You can use watch command , watch is used to run any designated command at regular intervals .

Open Terminal and type :

watch -n x <your command>

change x to be the time you want .

For more help using the watch command and its options, run man watch or visit this Link

For example : the following will list, every 60s, on the same Terminal, the contents of the Desktop directory so that you can know if any changes took place:

watch -n 60 ls -l ~/Desktop

 

Option #2:

You can also use this command in terminal, apart from option #1 :

while true; do <your_command>; sleep <interval_in_seconds>; done

Example

while true; do ls; sleep 2; done

This command will print output of ls at an interval of 2 sec.

Use Ctrl+C to stop the process.

There is few drawbacks of watch

  • It can not use any aliased commands.
  • If the output of any command is quite long, scrolling does not work properly.
  • There is some trouble to set maximum time interval beyond certain value.
  • watch will interpret ANSI color sequences passing escape characters using -c or --color option. For example output of pygmentize will work but it will fail for ls --color=auto.

In the above circumstances this may appear as a better option.

Option #3:

You can create your own repeat command doing the following steps;

First, open your .bash_aliases file:

$ xdg-open ~/.bash-aliases

Second, paste these lines at the bottom of the file and save:

repeat() {
n=$1
shift
while [ $(( n -= 1 )) -ge 0 ]
do
    "$@"
done
}

Third, either close and open again your terminal, or type:

$ source ~/.bash_aliases

Et voilà ! You can now use it like this:

$ repeat 5 echo Hello World !!!

or

$ repeat 5 ./myscript.sh