Detailed Usage of the Linux Watch Command

Introduction

<span><span>watch</span></span> command repeatedly executes a given command at fixed intervals (default every 2 seconds) and displays its output in the terminal. It is very useful for monitoring changing outputs, such as disk usage, memory usage, file changes, service status, etc.

Basic Syntax

watch [options] command

Common Options

  • <span><span>-n, --interval</span></span>: Allows specifying the interval between output updates, in seconds

  • <span><span>-d, --differences</span></span>: Highlights the differences between output updates

  • <span><span>-g, --chgexit</span></span>: Exits the watch command when the output of the user-defined command changes

  • <span><span>-t, --no-title</span></span>: Removes the title displaying the interval, command, and current time and date

  • <span><span>-b, --beep</span></span>: Plays a sound alert (beep) if the command exits with an error

  • <span><span>-p, --precise</span></span>: Attempts to run the command after the precise number of seconds defined by the <span><span>--interval</span></span> option

  • <span><span>-e, --errexit</span></span>: Stops output updates and exits the command upon an error after a key press

  • <span><span>-c, --color</span></span>: Interprets <span><span>ANSI</span></span> color and style sequences

  • <span><span>-x, --exec</span></span>: Passes the user-defined command to <span><span>exec</span></span>, reducing the need for extra quoting

  • <span><span>-w, --no-linewrap</span></span>: Disables line wrapping and truncates long lines

  • <span><span>-h, --help</span></span>: Displays help text and exits

  • <span><span>-v, --version</span></span>: Displays version information and exits

Example Usage

Display system time and date every 5 seconds

watch -n 5 date

Display system date and time at the default 2-second interval, highlighting changes

watch -d date

Exit on change

watch -g free

Hide the watch command header

watch -t date

For user-defined complex command parameters

  • Use <span><span>\</span></span> to wrap lines
watch -n 5 \
echo "watch command example output"
  • Enclose in quotes
watch -n 5 'echo "watch command example output"'

Monitor memory usage

watch -n 1 free -h

Check if a process is running

watch pgrep nginx

Observe the top 5 processes consuming CPU

watch -n 1 "ps -eo pid,comm,%cpu --sort=-%cpu | head -n 6"

Monitor the number of files in a folder

watch "ls | wc -l"

Highlight changes

watch -d ifconfig

Combine with grep for filtered output

watch "ps aux | grep nginx"

Use colors for better readability

watch -c "ls --color=always"

Monitor logs

watch tail -n 20 /var/log/syslog

For dynamic logs, <span><span>tail -f</span></span> is more suitable than <span><span>watch</span></span>.

Observe CPU dynamic frequency

 watch -n1 'grep "^cpu MHz" /proc/cpuinfo | sort -nrk4'

Please open in the WeChat client

Leave a Comment