Cheatsheet & Examples: watch
The watch command repeatedly executes a program or command and displays its output. This is useful for monitoring the output of a command that changes over time.
Monitor a Command's Output
Example Usage:
watch ls -l
What it does:
This will repeatedly run the ls -l command and display its output, updating the display every two seconds (the default interval).
Command-line Arguments Explained:
ls -l: The command to be executed.lslists files, and-lprovides a long listing format.
Specifying an Update Interval
Example Usage:
watch -n 1.5 df -h
What it does:
This will run the df -h command, displaying disk space usage, and refresh the output every 1.5 seconds.
Command-line Arguments Explained:
-n 1.5: Specifies the update interval in seconds.df -h: The command to be executed.dfreports disk space usage, and-hdisplays it in human-readable format.
Highlighting Changes
Example Usage:
watch -d -n 2 ps aux
What it does:
This command watches the output of ps aux, which lists all running processes. The -d option will highlight the differences between updates. The output refreshes every two seconds.
Command-line Arguments Explained:
-d: Highlights the differences between updates.-n 2: Specifies the update interval to 2 seconds.ps aux: The command to be executed.psis used to display process information.
Executing a Command and Ignoring Errors
Example Usage:
watch --no-title --errexit "ping google.com"
What it does:
Runs ping google.com repeatedly and displays its output without a header or error exit.
Command-line Arguments Explained:
--no-title: Suppresses the header that displays the command and update interval.--errexit: Exitswatchif the command being watched exits with a non-zero exit code (an error).ping google.com: The command to be executed.pingsends network packets to a specified host.
Using a Custom Command to Update the Screen
Example Usage:
watch -c cat /proc/loadavg
What it does:
This watches the output of cat /proc/loadavg and uses the 'cat' command to render the output to the screen, displaying the system load averages.
Command-line Arguments Explained:
-c: Use command for screen output.cat /proc/loadavg: The command to be executed.catdisplays the contents of a file./proc/loadavgprovides system load averages.

