Sometimes you need to monitor something without creating an elaborate solution. In many cases, shell may be all you need.
Option 1: watch
The shortest command is watch. It is great if you want to just visually inspect the output.
watch -n
For example:
watch -n 1 cat /proc/stat
It will use the entire terminal and redraw the output with each update. For this reason, it is not well-suited for saving the output.
Option 2: while
while loop is an alternative. It is not as accurate in timing as watch, but for simple tasks, it is not a problem. It uses shell built-in command to define an infinite loop in which the command is called, with sleep in each iteration.
while true; do
<command>
sleep <interval>
done
For example:
while true; do
cat /proc/stat
sleep 1
done
With this approach, you can easily redirect the output to file.
Good to know
watchis one of the standard utilities, but is not always available in embedded systems.!!is a history expansion syntax available in Bash. It is replaced by the last called command, so you can use it in a one-liner, like this:
cat /proc/stat
while true; do !!; sleep 1; done
trueis a command that does nothing and always succeeds, so it is great as an infinite loop condition.timeoutis useful when you need to stop execution after given period of time. The basic syntax istimeout <time>. So, if you runtimeout 2 sleep 5, it will stop after 2 seconds. It can be combined with the while loop, but there is a caveat. Sincewhileis a built-in shell command, not an executable, you cannot simply pass it totimeout. Instead, you need to call the interpreter (likeshorbash) with the-cswitch and insert the loop after that.
