Linux commands
Browse topics

Repeating a command with watch

Version
unversioned
Review
Draft

Summary#

watch runs a command repeatedly and shows the latest output on the full screen.

Syntax#

sh
watch -n 5 df -h
watch -d free -h
watch -g cat status.txt
watch 'ps -ef | grep [n]ginx'

-n sets the interval in seconds, 2 by default. -d highlights changes and -g exits when the output changes. watch passes its arguments to sh -c, so quote pipelines. Press Ctrl+C to leave.

Example#

watch needs a terminal, so this example uses the script utility to provide one and discards the screen drawing. Fedora packages script as util-linux-script.

sh
(
  set -eu
  dir=$(mktemp -d)
  writer=
  trap 'if [ -n "$writer" ]; then
      kill "$writer" 2>/dev/null || true
      wait "$writer" 2>/dev/null || true
    fi
    rm -rf -- "$dir"' EXIT

  echo waiting > "$dir/status"
  { sleep 2; echo done > "$dir/status"; } &
  writer=$!

  TERM=xterm timeout 20 script -q -e -c "watch -g -n 0.5 cat '$dir/status'" /dev/null \
    < /dev/null > /dev/null
  cat "$dir/status"
)

Expected output#

watch -g returns after the file changes, and the script then prints the new content.

Text
done

Common mistakes#

Without quotes, the shell applies a pipe or redirection to watch itself, so write watch 'command | filter'. watch needs a terminal and is a poor fit for scripts; use a loop with sleep there. Without one, procps-ng 4.0.6 stops with getchar(): Inappropriate ioctl for device. A command slower than the interval does not run in parallel with itself. Shell aliases are not available because the command runs in a new sh.

Version applicability#

This entry describes watch from procps-ng 4. macOS does not include watch.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0