Oftentimes you need to run a command every X seconds on Linux. Granted you can use cron but unfortunately, it does not handle time granularities of less than a minute.
The watch command on Linux allows you to run a program periodically. By default, the watch command has a repeat period of 2 seconds but this can be changed as per the requirement.
Say you would like to perform a periodic search of a file you expect to receive from a remote machine.The find command will look like :
find /home/ -name “test_results.txt”
Now in order to carry out this task every two seconds, you could use the watch command as follows :
watch find /home/ -name “test_results.txt”
linux watch command
Once you hit Enter you would see:
The snapshot above shows a header with information about the update interval along with the command being executed. To hide the header, use the -t option.
In case you want to change the default period of 2 seconds to another value, you can use the -n option with the watch command. This will indicate the period in seconds.
For instance, you would like to run an ‘free -m’ command every 5 seconds, you simply need to proceed as follows :
watch -n 5 free -m
if you have a script that needs to be executed every 10 seconds, you simply run the command :
watch -n 10 your_script.sh
The execution of the script above requires you to do a cd to the directory in which the script is located or you can simply mention the full path to your script.
You have seen how to use the watch command to perform repeated tasks. You can as well use a while or a for loop along with the sleep command. If you have other methods let us know.
If you like the content, we would appreciate your support by buying us a coffe. Thank you so much for your visit and support.