watch
Command: Monitor Command Output in Real-Time
Summary
The watch
command allows you to execute a specified command periodically and display its output in a full-screen format, providing a real-time view of changes.
Introduction
The watch
command is a powerful tool for monitoring the output of other commands on a regular basis. Instead of repeatedly running a command manually, watch
automates this process, updating the display at a specified interval. This is especially useful for observing changes in system status, file contents, or any other dynamic output.
Use case and Examples
Monitoring Free Disk Space
This command will executedf -h
every two seconds (by default) and display the output in a full-screen format, allowing you to monitor disk space usage. Watching CPU Usage
This command executesps aux --sort=-%cpu | head -5
every one second and shows the top 5 CPU-consuming processes. The -n 1
flag sets the interval to 1 second. The command is enclosed in single quotes to prevent shell interpretation of the pipe symbol. Monitoring File Changes
This command executesls -l
every two seconds and highlights the differences between successive updates. The -d
flag highlights the changes. Executing a Custom Script
This command executes themy_script.sh
script every two seconds. Ensure the script has execute permissions. Commonly used flags
Flag | Description | Example |
---|---|---|
-n, --interval <seconds> | Specifies the update interval in seconds. | watch -n 5 df -h (updates every 5 seconds) |
-d, --differences[=cumulative] | Highlights the differences between successive updates. With =cumulative , highlight changes between the first update and current. | watch -d ls -l (highlights differences) |
-t, --no-title | Turns off the header showing the interval, command, and current time at the top of the display. | watch -t df -h (removes the header) |
-x, --exec | Pass the command to sh -c which allows shell metacharacters. | watch -x 'free -m | grep Mem' (uses grep in the command) |
-p, --precise | Attempt run command in precise intervals. | watch -p date (Attempts to run date command in precise intervals) |
-g, --chgexit | Exit when the output of the command changes. | watch -g "ls -l /tmp" (Exits when /tmp content changes) |