The watch tool is used to execute a command repeatedly without having to use a loop construct.
Let’s again see a few examples to see the syntax and its features:
# execute the command every 5 seconds
root:~> watch -n 5 “ps -ef | grep bash | grep -v grep”
.
# execute the command every 5 seconds trying to keep precision (-p)
root:~> watch -n 5 -p “ps -ef | grep bash | grep -v grep”
.
# same as above but highlight the differences in output (-d)
root:~> watch -n 5 -p -d “ps -ef | grep bash | grep -v grep”
.
# same as above but beeps (-b) and exits (-g) when the output changes
root:~> watch -n 5 -p -b -g “ps -ef | grep bash | grep -v grep”
Nothing stops us from using a loop such as …
root:~> while [ true ]
> do
> ps -ef | grep bash | grep -v grep
> sleep 5
> done
… but the problem with that approach is that a small cumulative increment will be added with every iteration. After a number of iterations the lag will become noticeable. If we need the command/s executed exactly every x seconds or minutes, watch is the best tool available to us.