watch - Linux


Overview

The watch command in Linux is used to repeatedly execute a specified command at regular intervals, allowing the user to observe changes in the command’s output over time. It is particularly useful for monitoring disk space, running processes, and system resource usage when combined with commands like df, ps, and top.

Syntax

The basic syntax of the watch command is as follows:

watch [options] command

Arguments

  • command: The command you want to run repeatedly.

Options/Flags

  • -n, –interval seconds: Specifies the interval between executions of the command. The default is 2 seconds.
  • -d, –differences [cumulative]: Highlight the differences between successive updates. The cumulative option highlights growing differences.
  • -t, –no-title: Suppresses the header showing the command, current time, and refresh interval.
  • -b, –beep: Beeps if the command has a nonzero exit.
  • -e, –errexit: Exits if the command has a nonzero exit.
  • -g, –chgexit: Exit when the output of the command changes.

Examples

  1. Basic Usage: Watch the free disk space on the system every 2 seconds.
    watch df -h
    
  2. Custom Interval: Monitor the currently logged-in users every 5 seconds.
    watch -n 5 who
    
  3. Highlight Differences: Track changes in the list of running processes, highlighting new or exited processes.
    watch -d ps aux
    
  4. Exit on Change: Automatically exit when the content of a directory changes.
    watch -g ls /path/to/directory
    

Common Issues

  • Command Parsing Errors: Ensure quotes are used around commands that contain spaces or shell special characters.
  • Performance Issues: Very short intervals may degrade system performance or the readability of the command output.
  • Visibility in Differences: The -d option can be less effective if the command output changes substantially between each interval.

Integration

watch can be integrated with other commands for comprehensive system monitoring or scripted tasks. For example:

watch -n 10 'netstat -tulpan | grep LISTEN'

This combination is useful for monitoring open network ports dynamically, allowing for real-time network debugging.

  • tail: Follows the tail (end) of a file, usually for logs.
  • top: Provides a dynamic, real-time view of running processes.
  • ps: Reports a snapshot of current processes.

For further details and latest updates, you can refer to the official documentation at man watch on your system or the online manual pages.