Monday, September 8, 2014
1:42 AM

Using the watch command to run a script or command periodically

At times we need to run certain commands repeatedly and watch the output. It could be as simple as looking into the log files, to running some scripts.

For such repeated running of commands we can use the command watch.

Watch is a command that runs a command periodically at fixed intervals untill not stopped.

For example



The command "echo hello" will be run every two seconds and the output displayed on the terminal. The previous output will be replaced by the new output, thus in this case we will not see any change in the output.To quit we can use the keys "Ctrl + C".

To be able to see clearly the repeation of the command let us create a file called temp,using gedit, and enter the text "Hello" in it. Save the file and in the terminal go to the folder where the file is stored. Now execute the command



Now go back to the file and add the text "world" to it and save it. Go back to the teminal and see the change in the output.



We can see the updated text appear in the output.

By default the watch executes the command every 2 seconds, but that can be changed using the option "-n"



To be able to see the differences between consecutive outputs, we can make watch to highlight the differences in the output using the option -d

This option -d is very useful when we want to contiously look at logs and find out differences between two consecutive logs.

If we do not want to see the heading line which indicates the repetion interval, the command and the current time we can use the option -t.

0 comments:

Post a Comment