Skip to main content

Command Palette

Search for a command to run...

Cheatsheet & Examples: watch

Updated
2 min read

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. ls lists files, and -l provides 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. df reports disk space usage, and -h displays 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. ps is 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: Exits watch if the command being watched exits with a non-zero exit code (an error).
  • ping google.com: The command to be executed. ping sends 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. cat displays the contents of a file. /proc/loadavg provides system load averages.

More from this blog

Hong's Tech Blog

110 posts

The blog is older than you know. I prefer counting from the emergence of one integral anomaly to the emergence of the next, in which case this is the forth version.