Run a Linux command every so often with Watch

watch linux command

Automating certain tasks can be of great help to us, especially when they are tasks that involve working from the console. In our Linux distro we can have various tools to automate tasks, in addition to being able to write Bash scripts to execute a series of commands or actions without going one by one, and even add them to the system startup or schedule them to run on a certain date. or moment without us doing anything and in a transparent way.

In this article we will see how you can run a command every so often using watch. Watch is a command that can execute a program or another command every X seconds that we put on it. Thus we schedule the repetitive execution of a certain task. It can be especially practical for certain periodic consultations or for some maintenance tasks etc. You can apply it to anything as you can see here, the limit is your imagination ...

If you want the loop or repeat to end, you can use CTRL + C to finish the Watch action or just close the terminal window where it is running. The watch syntax is very simple and has this physiognomy:

watch [opciones] comando

For example, let's see a practical example It checks the space used in our partitions every 5 min (300 seconds). As to consult the used and free space of our partitions, type "df -h", because with watch it would be:

watch -n 300 df -h

You can check the watch man to see all the options it has, since it is quite flexible. In addition, we could redirect the query to a file so that the output is printed in a .txt for example:

 watch -n 300 df -h > espacio_usado.txt 

In this way, we can check the file used_space.txt where we will see that the same thing that the console would show us when typing df -h has been printed. Imagine the amount of tasks you can do ...


Leave a Comment

Your email address will not be published. Required fields are marked with *

*

*

  1. Responsible for the data: AB Internet Networks 2008 SL
  2. Purpose of the data: Control SPAM, comment management.
  3. Legitimation: Your consent
  4. Communication of the data: The data will not be communicated to third parties except by legal obligation.
  5. Data storage: Database hosted by Occentus Networks (EU)
  6. Rights: At any time you can limit, recover and delete your information.

  1.   David said

    Watch is a very useful command. I use it to control the temperature of my PC via terminal: «watch sensors».
    I already knew the command but I liked the article a lot (brief and well explained).

  2.   mircocaloghero said

    I really like these kinds of notes. Thanks

  3.   Soldier said

    It served me a lot