Website Vidya
Linux & ServersStep-by-Step Guide

watch Command in Linux: Monitor Command Output in Real Time

Learn watch command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

RR
Rajesh RayLead Systems Educator
Published:
11 min read
PDF Cheat Sheet
watch Command in Linux: Monitor Command Output in Real Time
AI Executive SummaryWebsiteVidya AI

11 min read

Learn watch command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

Key Highlights
  • What watch Does and When to Use It
  • Availability and Installation Across Linux Distributions
  • Command Syntax, Arguments, and Exit Status Codes
Grounded in full engineering runbookWebsiteVidya AI Engine

The watch command in linux is one of the most versatile and frequently utilized terminal utilities in a system administrator's toolkit. Rather than repeatedly pressing the up arrow to re-run status commands, piping loops through sleep, or installing complex monitoring dashboards, watch wraps any command or pipeline in a full-screen, self-updating terminal viewport.

Packaged within the core procps-ng project alongside ps, top, and free, watch periodically spawns the target program via a subshell, captures its standard output and error streams, and redraws the terminal display. It features built-in diff algorithms that visually highlight changing characters or words between updates, configurable refresh intervals down to fractions of a second, and trigger modes that automatically terminate execution the instant command output changes.

Whether you are watching disk free space during a critical database restore, monitoring active TCP connections during a stress test, tracking directory file counts during an archive extraction, or waiting for a remote host to come back online after rebooting, watch delivers effortless real-time observability.

Advertisement
watch Command in Linux: Monitor Command Output in Real Time — syntax, flags, and practical terminal workflow diagram
watch Command in Linux: Monitor Command Output in Real Time — command syntax, key options, and production workflow reference.

What watch Does and When to Use It

Architecturally, watch operates by executing an infinite loop structured around the nanosleep(2) system call and POSIX subshell execution. For each iteration, watch invokes sh -c "$*" (or directly executes the binary if no subshell characters are present) via fork(2) and execve(2), redirecting the target process's standard output and error through an anonymous pipe (pipe(2)). It buffers the output lines up to the terminal's visible row and column dimensions, which it dynamically queries via the TIOCGWINSZ ioctl.

To render the screen, watch writes standard ANSI escape sequences (such as \033[H\033[J or ncurses cursor repositioning) to position the cursor at coordinate (0,0) and overwrite the display buffer. When change highlighting (-d or --differences) is enabled, watch maintains two internal memory buffers: the previous screen matrix and the current screen matrix. It computes a character-by-character or word-by-word diff, applying ANSI reverse-video or color attributes to altered text elements before flushing the terminal buffer to stdout.

Under the hood, watch gathers runtime telemetry or dispatches control signals by reading virtual filesystems mounted at /proc and /sys, or by communicating with PID 1 (systemd) over D-Bus. Using flags such as -n <sec>, -d, -d=cumulative, -t turns raw process and service tables into actionable diagnostics during incident response.

Availability and Installation Across Linux Distributions

The watch utility is packaged in procps across mainstream Linux distributions. It is pre-installed on standard Ubuntu, Debian, RHEL, Rocky Linux, AlmaLinux, Fedora, and Arch Linux systems, while minimal container images may require manual installation:

Advertisement

Before running administrative tasks or automation scripts, verify whether watch is installed and inspect which binary path and version your shell resolves:

type -a watch
watch --version 2>/dev/null || man -f watch

# Illustrative output (reviewed against documentation)
watch is /usr/bin/watch
watch (procps)
# Debian / Ubuntu
sudo apt-get update && sudo apt-get install -y procps

# RHEL / Rocky / AlmaLinux / Fedora
sudo dnf install -y procps-ng

# Arch Linux
sudo pacman -S --noconfirm procps-ng

# Alpine Linux
sudo apk add --no-cache procps

Command Syntax, Arguments, and Exit Status Codes

watch [OPTIONS] COMMAND

The syntax for watch is concise: watch [OPTIONS] COMMAND. When passing simple single commands, arguments can be provided directly (e.g. watch -n 1 df -h). However, when executing pipelines containing pipe characters (|), output redirections (>), or shell logical operators (&&), the entire command string MUST be enclosed in quotes (e.g. watch -n 2 'ps aux | grep nginx') to prevent the invoking shell from interpreting the pipeline prematurely.

Key operational flags include -n <seconds> (or --interval) to set update frequencies, -d (or --differences) to highlight changing values in reverse video, -t (or --no-title) to hide the top status bar (displaying interval, command, and timestamp), -g (or --chgexit) to terminate watch automatically when the output changes, and -c (or --color) to interpret ANSI color and style escape sequences produced by the target command.

  • 0 — Clean exit requested by the user pressing 'q', Ctrl+C, or exit triggered by -g condition.
  • 1 — Operational failure, such as invalid argument syntax or failure to allocate screen memory.
  • 2 — Command execution error, or watch was terminated due to -e (--errexit) when the command failed.
  • * — If -e is passed, watch propagates the exact non-zero exit status code of the failing child command.

Important Options and Flags Reference

Option / FlagLong Form / ArgumentTechnical Behavior and Purpose
-n <sec>--interval=<sec>Sets the update interval in seconds; supports decimal fractions (e.g. -n 0.5). Default is 2.0s.
-d--differencesHighlights changed values between the current and previous updates in reverse video.
-d=cumulative--differences=cumulativeCumulatively highlights all characters that have changed since the initial update.
-t--no-titleSuppresses the top header bar showing update interval, command name, and current system time.
-c--colorInterprets ANSI color and style escape sequences produced by the child command.
-e--errexitFreezes updates and exits immediately if the command returns a non-zero exit status.
-g--chgexitExits watch immediately the instant the command's output changes from the previous run.
-b--beepBeeps (emits terminal BEL character \a) if the command exits with a non-zero return code.
-w--no-wrapPrevents long output lines from wrapping to the next line, clipping them at terminal boundaries.

A critical flag combination for modern terminal workflows is watch -c -d. Many modern CLI tools (such as ip -c a, systemctl, or git status) emit colored output; without the -c flag, watch prints raw escape sequences (e.g. ^[32m) or strips colors. Passing -c preserves colorful syntax while -d highlights text deltas.

Advertisement

The -g (chgexit) flag transforms watch from a purely interactive display monitor into an active automation trigger. For example, pairing watch -g -n 1 'systemctl is-active myapp' inside a deployment script causes watch to block until the service transitions from activating to active, upon which watch exits with code 0 and allows the deployment pipeline to proceed.

When combining short flags on the command line, POSIX and GNU utilities allow clustering boolean flags behind a single hyphen, provided any option taking an argument appears last. In automated shell scripts, using long-form GNU options where portable makes self-documenting code that is easier to audit during peer review.

Practical Basic and Advanced Usage Examples

1. Monitor Disk Space Consumption with Highlighted Changes

Run df -h every 1 second while highlighting changes to track real-time disk consumption during large file downloads or database imports.

watch -n 1 -d df -h /

# Illustrative output (reviewed against documentation)
Every 1.0s: df -h /                                   server: Thu Oct 22 19:50:04 2026

Filesystem      Size  Used Avail Use% Mounted on
/dev/nvme0n1p2  100G   42G   54G  44% /

watch refreshes every second; any change in the Used, Avail, or Use% columns is highlighted in reverse video.

2. Monitor a Complex Shell Pipeline with Quoting

Quote the entire pipeline inside single quotes to watch the top 5 memory-consuming processes without shell expansion errors.

watch -n 2 'ps aux --sort=-%mem | awk "NR<=6 {print \$2, \$4, \$11}"'

# Illustrative output (reviewed against documentation)
Every 2.0s: ps aux --sort=-%mem | awk "NR<=6 {print \$2, \$4, \$11}"   server: Thu Oct 22 19:50:10 2026

PID %MEM COMMAND
1420 14.2 /usr/bin/postgres
8901  8.4 /usr/bin/node
4102  4.1 /usr/sbin/mysqld
980   2.3 /usr/bin/dockerd
120   1.1 /usr/lib/systemd/systemd-journald

Wrapping the pipeline in single quotes ensures that pipes (|) and awk variables remain unexpanded until evaluated by watch's subshell.

3. Display Clean Output Without Header Bar

Use -t (--no-title) to hide the top status banner, dedicating the full terminal screen strictly to the command output.

watch -t -n 1 uptime

# Illustrative output (reviewed against documentation)
19:50:20 up 14 days,  6:42,  2 users,  load average: 0.45, 0.52, 0.61

The -t flag removes the 'Every 1.0s: ...' header, creating a clean display suitable for embedded terminal panes or status panels.

4. Preserve ANSI Colors from Commands with --color

Pass -c to allow commands like ip or git to display their rich colored terminal status output.

watch -c -n 2 ip --color -brief address

# Illustrative output (reviewed against documentation)
Every 2.0s: ip --color -brief address                 server: Thu Oct 22 19:50:30 2026

lo               UNKNOWN        127.0.0.1/8 ::1/128
eth0             UP             192.168.1.50/24 fe80::215:5dff:fe00:1a2b/64
docker0          DOWN           172.17.0.1/16

The -c switch instructs watch to parse and render ANSI color codes (green for UP, red for DOWN) rather than stripping them.

5. Exit Automatically the Instant Command Output Changes

Use -g (--chgexit) to monitor a background compilation or job and exit as soon as the status changes.

watch -g -n 1 'cat /var/run/build_status 2>/dev/null || echo "pending"'
echo "Build status changed! Proceeding with next step..."

# Illustrative output (reviewed against documentation)
Build status changed! Proceeding with next step...

watch polls the file every second. As soon as the output differs from the initial run, watch exits, releasing the script to continue.

6. Track Directory Inode and File Growth in Real Time

Monitor the number of files accumulating in an upload or spool directory during high-volume batch processing.

watch -n 0.5 'ls -1 /var/spool/incoming | wc -l'

# Illustrative output (reviewed against documentation)
Every 0.5s: ls -1 /var/spool/incoming | wc -l         server: Thu Oct 22 19:50:45 2026

1428

Using fractional seconds (-n 0.5) provides high-frequency 500ms updates to monitor fast incoming queue throughput.

Real-World Workflows, Pipelines, and Shell Automation

Real-Time Tracking of Data Migration, Disk Space, and Directory Inodes

Monitor storage volumes, inode consumption, and directory file counts during large-scale rsync or database export operations.

#!/usr/bin/env bash
# Monitor target backup filesystem and file count simultaneously
watch -n 1 -d '
  echo "=== Disk Space and Inode Usage on /mnt/backup ==="
  df -h /mnt/backup
  df -i /mnt/backup
  echo ""
  echo "=== Top 5 Largest Files Being Written ==="
  find /mnt/backup -type f -exec ls -lh {} + 2>/dev/null | sort -k5 -hr | head -n 5
'

# Illustrative output (reviewed against documentation)
Every 1.0s: ...                                       server: Thu Oct 22 19:51:00 2026

=== Disk Space and Inode Usage on /mnt/backup ===
Filesystem      Size  Used Avail Use% Mounted on
/dev/sdb1       500G  182G  294G  39% /mnt/backup
Filesystem       Inodes  IUsed   IFree IUse% Mounted on
/dev/sdb1      32768000 482010 32285990    2% /mnt/backup

=== Top 5 Largest Files Being Written ===
-rw-r--r-- 1 root root  42G Oct 22 19:50 /mnt/backup/postgres_dump.sql
-rw-r--r-- 1 root root  18G Oct 22 19:48 /mnt/backup/redis_dump.rdb

Combining disk capacity, inode availability, and active file sizes inside a multi-line watch command provides complete visibility during migrations.

Automated Service Recovery Verification with Exit-on-Change Trigger (-g)

Use watch in an automated post-maintenance script to block execution until a cluster service recovers health checks.

#!/usr/bin/env bash
set -euo pipefail

echo "Restarting payment-gateway microservice..."
sudo systemctl restart payment-gateway.service

echo "Waiting for health endpoint to report healthy..."
# watch exits the instant curl returns 200 OK instead of 502/000
watch -g -n 1 '
  STATUS=$(curl -s -o /dev/null -w "%{http_code}" http://127.0.0.1:8080/healthz || echo "failed")
  [ "${STATUS}" = "200" ] && echo "HEALTHY" || echo "WAITING"
'

echo "Service is fully recovered and accepting traffic. Proceeding with rolling deploy."

# Illustrative output (reviewed against documentation)
Restarting payment-gateway microservice...
Waiting for health endpoint to report healthy...
Service is fully recovered and accepting traffic. Proceeding with rolling deploy.

Using watch -g to poll HTTP endpoints creates an elegant, self-contained health check loop in deployment automation scripts.

Pipelines, Redirection, Quoting, and Shell Expansion

When embedding watch inside shell pipelines (|), conditional chains (&& and ||), or command substitutions ($(...)), the calling shell performs tilde expansion, variable interpolation, and globbing before invoking the binary. Always wrap paths, patterns, and variables in quotes so whitespace and wildcard characters (*, ?) are not expanded prematurely, and use set -euo pipefail in unattended scripts.

Permissions, Security Implications, and Safe Execution

Be cautious when constructing command strings for watch using variables derived from untrusted user input. Because watch invokes sh -c under the hood to parse command lines, unescaped shell metacharacters (;, &&, `, $()) introduce dangerous command injection vulnerabilities.

When running sudo watch COMMAND, remember that the subshell spawned by watch inherits root privileges and continues executing the command as root on every interval. Ensure that the command being watched cannot be replaced or modified by unprivileged users in shared directories (such as /tmp).

GNU/Linux, BSD, and BusyBox Implementation Differences

The standard watch command on Linux is part of procps-ng. On FreeBSD and macOS, the native watch command has a completely different purpose: it snoops on another user's tty terminal line. To achieve Linux-like command watching on macOS or FreeBSD, users must install the GNU version (brew install watch or pkg install cmdwatch).

On Alpine Linux and minimal embedded distributions, BusyBox includes a lightweight implementation of watch. The BusyBox applet supports basic interval timing with -n and title suppression with -t, but typically lacks advanced flags like -c (color), -g (chgexit), and -d (differences).

Troubleshooting Common Errors and Diagnostics

Pipes (|) and redirections (>) fail or execute only once when starting watch

Root Cause: The command pipeline was not enclosed in quotes; your interactive shell parsed the pipe before passing the first argument to watch.

Resolution: Always enclose the entire command pipeline in single quotes so watch passes it to its internal subshell.

# Wrong: watch -n 1 ps aux | grep nginx
# Correct:
watch -n 1 'ps aux | grep nginx'

Shell aliases and custom bash functions are reported as 'command not found'

Root Cause: watch executes commands using a non-interactive subshell (sh -c), which does not load your interactive ~/.bashrc aliases or functions.

Resolution: Export the function with export -f and invoke bash -c, or use the raw binary path instead of the alias.

export -f my_function
watch -n 1 'bash -c my_function'

Colors appear as garbled characters like ^[[32m in watch output

Root Cause: The target command is outputting ANSI color codes, but watch was launched without the -c (--color) flag.

Resolution: Pass the -c flag to instruct watch to interpret ANSI escape sequences.

watch -c -n 1 'ip --color a'

Authoritative References and Official Documentation

Frequently Asked Questions

Quick answers to common questions and configurations

4 FAQs
Press 'q' or 'Ctrl+C' inside the watch terminal window to terminate execution and return to your shell prompt.
Yes. The -n flag supports decimal fractions. For example, 'watch -n 0.2 COMMAND' updates every 200 milliseconds (5 times per second).
watch spawns a subshell with a clean environment. If you need specific variables, declare them inside the quoted command string: watch -n 1 'MY_VAR=test /path/to/script.sh'.
watch -d highlights changes only between the immediate previous run and the current run (clearing highlights once values stabilize). watch -d=cumulative permanently highlights any character that has changed at any point since watch was launched.
RR
Written byVerified Author

Rajesh Ray

I’m Rajesh Rai, a full-stack developer, Linux administrator, and technology enthusiast passionate about making complex technology easier to understand and use.

SPAM-FREE MODERATED DISCOURSE

Join the Conversation & Perspective

Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.

AT
MP
JV
+2

No comments on this guide yet. Be the first to share your thoughts or ask a question!

Recommended Reading10 Guides

Related Technical Guides

Tested runbooks, server administration walkthroughs, and troubleshooting guides

Featured Infrastructure PartnerUp to 75% OFF + 3 Months Free

Supercharge Your Linux & Cloud Workloads with Hostinger

Deploy high-speed NVMe KVM VPS, Docker containers, and LiteSpeed-accelerated WordPress servers in under 60 seconds with full root access, dedicated IPv4, and 24/7 technical support.

Pure NVMe SSD StorageFull Root Access & SSHFree Domain & Unlimited SSL99.9% Uptime SLA
Plans from$2.99/mo
Claim Hostinger DealAffiliate link • Special discount applied at checkout