Short Bytes: Have you ever needed to run a command every couple minutes to check on something? Say you need to watch a RAID rebuild or watch a log in real time, but need to search or filter it first. That takes a lot of specialized tools, one for each task really. But using watch command this can be achieved easily.
What watch does is it runs the command in a loop, but clears the terminal before running it each subsequent time, and additionally, displays the interval, command, and date/time as the first line. The default interval is two seconds, but this can be manually set using the -n flag with a lower limit of one-tenth of a second.
Here, below, we run the free (a memory usage reporting tool) command every five seconds.
As you can see, we were able to pass in the -m (display in megabytes) flag to free without confusing watch. This is because all arguments after the first argument, which is a non-option, are passed to the executed command. This gives you some freedom to pass commands without the need of quotes, though, in the cases where piping and redirection are used, quotation marks will be required otherwise the output of watch will be what’s piped.
There are many options that can be passed to watch, like -t to remove the header information, or -d to highlight the differences between each interval. Below is the full list according to the documentation.
|-b, –beep||beep if command has a non-zero exit|
|-c, –color||interpret ANSI color and style sequences|
|-d, –difference||highlight changes between updates|
|-e, –errexit||exit if command has a non-zero exit|
|-g, –chgexit||exit when output from command changes|
|-n, –interval||seconds to wait between updates|
|-p, –precise||attempt run command in precise intervals|
|-t, –no-title||turn off header|
|-x, –exec||pass command to exec instead of “sh -c”|
|-h, –help||display help and exit|
|-v, –version||output version information and exit|
With these options, it’s easy to see how we can combine watch and a little bit of scripting with other tools (or sysadmin-fu as some like to call it) to create complex monitoring tools that are custom tailored to our specific needs.
Show us how you watch in the comments below.
Also Read: Linux Lexicon — Input And Output With Pipes And Redirection In Linux