How to Run or Repeat a Linux Command Every N Seconds

Frontend.LA Engineers

Jan, 19

Regardless of your job title if at some point you had to SSH into a Linux server and run a command repeatedly you've probably thought - "Isn't there a command that can do this". e.g. I had to check the status of my docker to see how long does it take to build a next.js app. I did keep doing the "up arrow" + "Enter" to run "docker ps" which got irritating after a while. This isn't about a cron command running in the background, I wanted to run a command and literally watch it every second.

After a while when the "up arrow" + "Enter" approach got monotonous I finally pressed the "up arrow" on my standup desk,  put in the effort to stand up, I knew it was time to open a new tab and look this up.

What blew my mind was - the command line utility to watch the progress or continuously running command was called "watch". 

If that didn't blow your mind let me present another analogy it's like if facebook was on day 1 went live on

Ok jokes aside let's see how to use the watch command

To run a bash script every 10 seconds you'd create a bash file let's say and type

watch -n 10

Of course, if you replace 10 with 5 the same bash file will be executed every 5 seconds while showing the result  as well as the time in the terminal

But what if you didn't want to create a bash file and run a simple command like " docker ps" and watch it. Then you'd do

watch -n 1 docker ps

Isn't that simple and awesome?