Back to Explore
GuideVibeFix editorialUpdated Dec 2, 2026

watch From Zero: Run a Command Every Few Seconds and Watch the Screen for Changes

Waiting for a build, a log, a status flip — much of the time you don't need a script, just one command that re-runs every few seconds and pins the result to the screen. This guide runs every watch command for real on procps-ng 4.0.4: the default interval, the header, -d highlighting, -g stop-on-change, -q stop-on-unchanged, -e freeze-on-error — plus the measured finding that -e's exit code is always 8, whatever the manual promises.

Real photograph of a monitor showing a multi-pane terminal with system logs in a dark room (illustrative photo)

Waiting for a build to finish, watching a log file, checking how much disk is left, confirming whether a process is still alive — much of the time you do not need a script. You just need one command to run something every few seconds and pin the result to the screen. That is what watch does: it runs a command on a schedule, shows the output full-screen, and lets you see the moment it changes. This guide runs every command in it for real, on watch from procps-ng 4.0.4: the default interval, the header, change highlighting, stop-on-change, stop-on-unchanged, and freeze-on-error, plus a full set of traps that are easy to fall into. The conclusion first: watch's real skill is not "running commands" but "comparing output" — it does not judge right or wrong; it runs on schedule, compares, and stops by the rules. Learn it, and you gain a pair of eyes that never need to blink — and, unlike a loop you wrote in a hurry at two in the morning, one that behaves the same way on every machine you run it on. It costs nothing to install: watch ships with procps-ng, which is already on virtually every Linux system you will ever log into.

The simplest usage is watch ls -l: run ls -l every two seconds and show the result full-screen. The default interval is 2 seconds, and watch keeps running until you press Ctrl+C. At the top of the screen is a header line, which in our measured transcript looks like this: Every 1.0s: echo hello-watch, followed by the hostname and the current date. The header tells you three things at once: how often it runs, what command it runs, and what time it is now. Only the first screenful is shown — if the output is too long it gets cut off, and you only see the beginning. If you do not want the header, add -t (--no-title): the screen holds only the command's output, much cleaner. In this guide's demo, most commands carry -t so the output is easier to read.

Change the interval with -n (--interval), in seconds, decimals allowed. watch -n 1 'date +%T' runs once a second, and the header becomes Every 1.0s. The manual states the bounds: anything below 0.1 seconds is treated as 0.1 seconds, anything above 2,678,400 seconds (31 days) is treated as 31 days; both . and , work as the decimal separator, for different regional conventions. There is also an environment variable, WATCH_INTERVAL, which changes the default interval persistently without writing -n every time. But note this: the interval is counted from when the previous round finished, not from when it started. If the command itself is slow — say it takes 3 seconds — and the interval is 1 second, the actual rhythm will be slower than you expect. If you want "strictly once every N seconds", add -p (--precise): the interval is then counted from the start of the previous round. Even then, -p cannot fix the underlying contradiction of a command slower than its interval; it only makes the rhythm more even.

The most useful thing watch does is -d (--differences): it highlights the parts where two consecutive outputs differ. Here is how the demo ran it: first write 10 into a file, then run watch -n 1 -t -d 'cat n.txt', and 2.5 seconds later change the file to 11. In the transcript the screen first shows 10, and after the change 11 is highlighted (in the terminal transcript the two values run together as 1011). If you want to see "everything that has changed since the beginning", use -d=permanent (also written -d1 or --differences=1): every place that has changed since the first round stays highlighted. That option is best for watching something that changes slowly: new lines appearing in a log, a number creeping upward, a state that comes and goes. One caveat: -d can only highlight changes you can see — output beyond the first screen, cut off by the display, is not covered.

-g (--chgexit) is "stop when it changes": the moment the output changes, watch exits. The demo ran like this: the file counter.txt first held 1; we ran watch -n 0.5 -t -g 'cat counter.txt'; two seconds later the file became 2; watch saw the output change from 1 to 2 and exited immediately, with --- pty exit code: 0 --- in the transcript. This option fits "wait for a change" scenarios: wait for a file to appear, wait for a service's status to flip, wait for a build artifact to be generated — the moment the change appears, watch exits and your script can carry on. The same "visible" limitation applies: the manual states that changes off-screen do not trigger an exit — if your terminal is too small and the output too long, a change that happens outside the visible area will not stop watch.

-q (--equexit) is the opposite, "stop when it stops changing": if the output stays the same for N consecutive rounds, watch exits. The demo ran watch -n 0.5 -t -q 2 'echo fixed'; the output is always fixed, so after two unchanged rounds watch exited, again with --- pty exit code: 0 ---. This option fits "wait for it to settle" scenarios: wait for a log to stop scrolling, wait for a number to stop jumping, wait for a process that keeps retrying to finally stop. -g and -q are a pair: one waits for "change", the other waits for "no change". Both exit with code 0 — which is to say, exit code 0 only means watch ended normally by its rules; it says nothing about whether the command itself succeeded. That sentence is worth remembering; it comes up again below.

-e (--errexit) is "freeze on error": once the command returns a non-zero exit code, watch stops updating, freezes the last screen in place, and waits for you to press any key before exiting. The demo ran watch -n 0.5 -t -e 'false'; false always returns 1, and the screen showed the message command exit with a non-zero status, press a key to exit; after a keypress, watch exited. Here is a measured finding that has to be reported honestly: the manual says "watch's exit code will be the code the command exited with", but on procps-ng 4.0.4 we measured three times — the commands were false (exits 1), exit 3, and exit 42 — and after a keypress watch's exit code was --- pty exit code: 8 --- every time. In other words, at least in this version, the -e exit code is not reliable; do not use it in a script to decide how the command failed. If you need to branch on watch's exit code in a script, the 0 from -g or -q is enough; -e is for a human sitting in front of the screen.

The remaining options are worth picking up as needed. -c (--color) makes watch interpret ANSI colour and style sequences in the command's output — without it, coloured output shows up as raw escape codes; conversely, -C (--no-color) forces no interpretation. -b (--beep) beeps when the command returns non-zero, handy for leaving watch running in the background and listening for it. -x (--exec) skips sh -c and calls exec directly, which starts faster, at the cost of losing shell features (variables, wildcards, pipes). -f (--follow) does not clear the screen each round but scrolls the output downward like tail -f — but it is incompatible with -d, -g, and -q, the options that watch screen content, so they cannot be combined. -w (--no-wrap) truncates long lines instead of wrapping them. -r (--no-rerun) stops watch from immediately re-running when the terminal size changes. The keyboard has a few controls too: space runs the command immediately without waiting for the next round, s takes a screenshot (saved in the current directory, or the directory given by -s/--shotsdir), and q quits.

Watch's exit codes deserve their own section, because they are the easiest thing to misunderstand. The EXIT STATUS section of the manual says: 0 means success — but that success does not represent the command's exit code; 1 means "errors unrelated to command execution"; 2 means "errors related to command execution and management" (not the command's exit code); only with --errexit does watch return the command's exit code — and the previous section already showed that this promise does not hold in practice (three runs, all 8). So the correct understanding is: watch's exit code only tells you how watch itself did; how the command did is something you read off the screen. Treating the 0 from watch some-command; echo $? as "the command succeeded" is the most common beginner mistake.

There are a few more traps that the manual states plainly but first-time users keep falling into. First, pipes and redirections inside the command need quotes: watch -n1 'grep "^cpu MHz" /proc/cpuinfo | sort -nrk4' — the quotes are a shell feature; without them, the outer shell interprets the pipe first, and watch receives something other than the command you wanted. That is the manual's own example from its EXAMPLES section. Second, POSIX option processing stops at the first non-option argument: options written after the command are not recognized by watch — in watch ls -l -d, the -d belongs to ls, not to watch. Third, non-printing characters in the output are stripped by watch; to see them, add cat -v inside the command. Fourth, watch shows only the first screenful of output; when the output is too long, you cannot see the rest at all — that is when to switch to -f scrolling, or to stop using watch altogether.

When to use watch and when not to is also worth one clear sentence. Watch fits scenarios where "a person is watching": waiting for a build, a deployment, a log, a status flip. It does not fit scenarios where nobody is watching: with no one looking, change highlighting and frozen screens are all wasted — what you want then is a cron scheduled task, or a loop that writes results into a log. Watch is also not a monitoring tool: it has no alerts, no history, no retention, and closing the terminal loses everything. Treat it as a "temporary telescope", not a "security camera", and you will not use it in the wrong place.

Finally, the relationship between watch and snapshot commands like ps and df. ps takes a snapshot of processes; df takes a snapshot of disk. Watch is "take a snapshot every few seconds, then lay two of them on top of each other and compare". The previous guide on ps covered "what processes are doing at one moment"; this one covers "how processes are changing over these few seconds". Together they are complete: first use ps to see the present clearly, then use watch -d to see the change clearly. The full demo transcript is in demo285_watch_transcript.txt: the version line watch from procps-ng 4.0.4, the header Every 1.0s: echo hello-watch, -g changing 1 to 2 with exit code 0, -q on fixed with exit code 0, -e's freeze message with exit code 8, -d changing 10 to 11, and the final --- done (work dir removed, no file left) ---. The work directory is deleted when done; no files are left behind.

Here are a few real scenarios, so you can see where watch belongs. The first is waiting for a build: you changed code and ran npm run build; the build takes three minutes; instead of waiting idly, run watch -n 5 ls -lh dist/ — the moment the artifact appears and its size changes, you see it on screen. The second is watching a log: a service just restarted and you want to know whether it really came up; watch -n 2 'tail -5 app.log' is far easier than pressing the up arrow and Enter over and over. The third is watching disk: you are downloading a large model file, and watch -n 10 df -h lets you see the free space tick downward, so you know where you stand. The fourth is waiting for a status flip: you submitted a deployment and are waiting for the health check to go from failing to passing; watch -n 5 -g 'curl -s -o /dev/null -w "%{http_code}" localhost:3000/health' exits by itself the moment the status code becomes 200. What these scenarios share is that what you are waiting for is not a fixed point in time but a "change", and you do not know when the change will come — which is exactly why watch exists.

How long the interval should be is a decision that deserves some thought. Too short, and you waste CPU and flicker the screen until your eyes hurt; too long, and you miss the change. The rule of thumb is: things a person is watching, 0.5 to 2 seconds is comfortable — build output, log tails, status codes all sit in that range. Things that change slowly, 10 to 60 seconds is enough — disk space, backup progress, a long task's output; checking once a minute costs nothing. There is another case: the command itself is slow. A check that takes 3 seconds a round makes a 1-second interval meaningless, because watch waits for the previous round to finish before the timer starts, so the actual rhythm becomes one round per 3 seconds. Then either set the interval longer than the command takes, or add -p so the interval counts from the previous round's start — but -p cannot rescue the fundamental contradiction of a command slower than its interval; it only makes the rhythm more even.

Many people ask: why not just write a loop instead of using watch? You can, but it is more work than watch. while true; do clear; date; ls -l; sleep 2; done also refreshes every two seconds, but you have to write the clearing yourself, do the timing yourself, and handle "stop when it changes" yourself. Watch bundles all of that: the header records the time for you, -d compares the changes for you, -g and -q decide when to stop for you, and -e freezes the failing screen for you. More importantly, watch's behaviour is predictable: it is exactly the options in the manual, the same on any machine. Every detail of a hand-written loop — whether to use clear, how signals are handled, how output is truncated — is something you have to worry about yourself. The value of a tool is that it collapses those repeated decisions into a few options.

Colour deserves its own word, because it decides whether you can understand the screen at a glance. Much command output is coloured: the red and green of a test runner, the file-type colours of ls, the severity colours in a log. By default watch interprets those ANSI colour sequences (interpreting them is part of the default behaviour), so the red and green on screen look the same as when you run the command directly. If you see a pile of ^[[32m garbage on screen, the colours are not being interpreted correctly, and adding -c explicitly fixes it; conversely, if you want to see the raw escape codes themselves — for example while debugging a program that outputs colours — add -C to force no interpretation. You barely notice this option on a normal day; when something goes wrong it can save half an hour.

The screenshot feature is the most easily overlooked part of watch: press s and the current screen is saved as a file, in the current directory or the directory given by --shotsdir. When is that useful? You are watching a state that flashes past — an error that appears for two seconds and is then covered by the next round's output — and pressing s keeps it for later, unhurried reading. It works even better with -d: first let the changes highlight themselves, then take the screenshot as evidence. For anyone who writes postmortems, files bug reports, or keeps records, this is a handy little feature: no separate screen recording, no phone photograph of the monitor, just one keypress.

There is another easily overlooked detail: the command watch runs executes inside sh -c, not inside your current shell. That means two things. First, the variables, aliases, and functions the command uses belong to sh's world, not your interactive shell's — an alias defined in your .bashrc is not recognized inside watch; either write the full command, or put the logic in a script file and let watch run that. Second, the command's exit status and signal handling also follow sh -c's rules. To bypass that layer, use -x and let watch exec the command directly, skipping the shell — but at the cost of losing pipes, redirections, and wildcards entirely. Most of the time, the least troublesome choice is to wrap the command in quotes honestly and let sh -c run it.

What makes watch genuinely powerful is that it wraps around any command and turns it into a universal "change detector". Almost every command from earlier guides in this series can be put inside watch and seen again: watch -n 2 ps aux --sort=-%cpu | head to see who is eating CPU, watch -n 5 df -h for disk, watch -n 1 'ss -tlnp' for ports, watch -n 2 'free -h' for memory. Each one on its own is only a snapshot; inside watch it becomes a recording. When you are debugging, that "recording" is often far more useful than a "snapshot": whether a process is "always using CPU" or "bursting every few seconds" cannot be seen from one snapshot, but ten seconds of watch makes it obvious. Treat watch as the "repeater" in your toolbox, and every command you learned before levels up one notch.

Terminal size changes affect watch too, and the manual has a line for it. By default, when the terminal window grows or shrinks, watch immediately re-runs the command and redraws at the new size; if you do not want that, add -r (--no-rerun), and a size change will not trigger a re-run — it waits for the next round. A related option is -w (--no-wrap): by default long lines wrap onto the next line, but with it, long lines are truncated and only the part that fits is shown. Neither option is used every day, but when you keep dragging the window around, or when the output has very long lines, they save a lot of eye strain. Together with the -s screenshots and the -b beep discussed earlier, these are all "small but handy" designs: watch does not have many options, but each one is built for the scenario of "a person sitting in front of the screen, watching".

Watch's output is for people to look at, not for files — what is on the screen is gone when you close it. If you want to keep each round's output, you have to do it inside the command yourself. The manual's EXAMPLES section gives exactly such a pattern: watch -n10 -p -d '{ date; for i in 10.0.0.31 10.0.0.32 10.0.0.33; do R=OK; ping -c2 -W2 "$i" &>/dev/null || R=FAIL; echo "$i: $R"; done } | tee -a ~/log' — braces group several commands into one, the pipe hands them to tee -a to append into a log file, and the screen still refreshes every 10 seconds. That one line uses several things from this guide at once: quotes around the whole command, -p so the interval counts from the previous round's start, -d to highlight changes, and tee -a to keep a record. Treat it as a template: when you need a record, put tee -a after the command; when you only need to look, add nothing.

One more practical habit is worth building: pair watch with a terminal multiplexer when the thing you are watching will outlast your attention span. If you start watch inside tmux or screen and detach, it keeps running on the server while you go and do something else; reattach later and the current screen is waiting for you. That does not turn watch into monitoring — there is still no alert and no history — but it does solve the common annoyance of a watch session dying when your SSH connection drops. The combination is simple: open tmux, run watch, detach with Ctrl+B then D, and reattach with tmux attach whenever you want to check. For a build that takes twenty minutes, that is a much calmer workflow than keeping a terminal window open and staring at it.

It is also worth knowing what watch is not, by comparison with the tools people often confuse it with. It is not tail -f: tail follows a growing file, watch re-runs a command. It is not a loop in a shell script: a loop gives you control, watch gives you a screen. It is not a monitoring system like Prometheus or Nagios: those keep history, send alerts, and run when nobody is looking; watch keeps nothing and alerts no one. And it is not a dashboard: a dashboard shows many things at once, watch shows one thing, very clearly. Each of those tools has its place, and watch's place is the narrow one: one command, one screen, one person watching. Knowing the boundary is what lets you reach for it without hesitation when it fits, and without regret when it does not.

A note on how this guide's demo was produced, because it affects how you read the transcript. Watch is a full-screen ncurses program: it needs a real terminal, and a plain command pipeline has none. The demo was run through a small Python driver that allocates a pseudo-terminal, feeds watch keystrokes on a schedule, strips the ANSI escape codes, and prints the cleaned output — which is why the transcript's exit lines read --- pty exit code: 0 --- instead of a plain shell exit code. The transcript is a faithful record of what appeared on the screen, including the odd-looking concatenated 1011 where the old and new values overlapped in the recording. One thing the harness could not do reliably was make watch quit by pressing q — so this guide does not claim that as demonstrated. The manual says q quits; the demo does not pretend to have shown it.

There is one more setting where watch earns its keep, and it is the one this publication cares about most: pairing with an agent. When an agent runs a long build, a test suite, or a migration, the human in the loop wants to know what is happening without asking the agent for a status report every minute. Watch is the human's side of that partnership: run the agent's command inside watch in a second terminal, and the progress is visible at a glance — the log tail, the artifact size, the status code — while the agent keeps working in its own session. The agent does not need to know watch exists. The human just needs a screen that updates itself. That division of labour — the agent does the work, watch shows the work — is a small example of a larger principle: the best tools for working with agents are often the oldest ones, because they were built for a person watching a screen, and that is still what the person is doing.

Scope note: this guide covers only watch (procps-ng 4.0.4, the watch(1) manual) — running a command on a schedule, showing its output full-screen, and comparing consecutive rounds. Its boundaries with previously published guides are as follows: the ps guide covers a process snapshot at one moment, not scheduled repetition or change comparison; the df and du guides cover disk space, not output monitoring; the free guide covers memory, not watch; the head-tail and tee guides cover handling output streams, not scheduled execution. Watch's -f scrolling mode is mentioned here only, not developed — for scrolling output streams, see the head-tail guide.

One watch cycle: run the command, compare with the previous output, wait one interval and run again; the -g, -q and -d options all branch off the comparison step

Views 0Comments 0

Comments (0)

ME
0/1000
Loading comments...

Sources

Browse projectsPublish your project

Related articles

Real photograph of a fingertip with a glowing fingerprint pattern overlaid (illustrative photo)
Guide
sha256sum From Zero: Give Every File a Fingerprint, Then Verify It Before You Trust It

Downloaded an installer or a model weights file — how do you know it arrived intact? sha256sum computes a 64-hex fingerprint for any file: change one byte and the fingerprint changes completely. This guide runs every command for real on GNU coreutils 9.4: fingerprints, manifests, bulk checks, deliberate tampering, a missing file, quiet mode — plus the measured finding that --ignore-missing skips missing files, not mismatched ones.

Developer WorkflowTool TipsLearning & Career
Real photograph of an open hard disk drive showing the platter and read/write head (illustrative photo)
Guide
du From Zero: Disk Full? First See Who Is Taking the Space

df says the disk is full; it never says who took the space. du does. This guide runs every command for real on GNU coreutils du 9.4: -sh totals, -d drilling, block rounding (a 100-byte file takes 4.0K), sparse files (100M apparent, 0 on disk), -b vs --apparent-size, --exclude, and the three reasons du and df disagree — plus a full-disk investigation flow.

Developer WorkflowTool TipsLearning & Career
Real photograph of a computer monitor showing terminal windows with system output (illustrative photo)
Guide
ps From Zero: What Every Process Is Doing, at a Glance

Which process is eating memory, who started whom, which one died but was never collected? ps answers all of it with one snapshot. This guide runs every command for real on procps-ng ps 4.0.4: default selection, Unix vs BSD vs GNU options, -o custom columns, --sort, --forest trees, the full STAT alphabet, a live zombie demo, and headerless output for scripts — plus the four classic traps.

Developer WorkflowTool TipsLearning & Career