Repeatedly running shell commands

Sometimes you need to monitor something without creating an elaborate solution. In many cases, shell may be all you need.

Option 1: watch

The shortest command is watch. It is great if you want to just visually inspect the output.

watch -n  

For example:

watch -n 1 cat /proc/stat

It will use the entire terminal and redraw the output with each update. For this reason, it is not well-suited for saving the output.

Option 2: while

while loop is an alternative. It is not as accurate in timing as watch, but for simple tasks, it is not a problem. It uses shell built-in command to define an infinite loop in which the command is called, with sleep in each iteration.

while true; do
	<command>
	sleep <interval>
done

For example:

while true; do
	cat /proc/stat
	sleep 1
done

With this approach, you can easily redirect the output to file.

Good to know

  cat /proc/stat
  while true; do !!; sleep 1; done