Linux watch command
What is the watch command
watch is a very useful command-line tool in Linux systems; it periodically executes a specified command and displays the output full-screen. This command is especially suitable for monitoring system status, file changes, or any command output that needs continuous observation.
Basic syntax of the watch command
watch [选项] 命令
Detailed explanation of common options
| Option | Description | Example |
|---|---|---|
-n or --interval |
Set the refresh interval (in seconds); default is 2 seconds | watch -n 5 date |
-d or --differences |
Highlight the differences between two refreshes | watch -d ls -l |
-t or --no-title |
Do not show the time, command, and interval information at the top | watch -t free -h |
-b or --beep |
Beep when the command exits with a non-zero status | watch -b ping example.com |
-e or --errexit |
Stop updating and exit when the command fails | watch -e ./check_status.sh |
-g or --chgexit |
Exit when the command output changes | watch -g ls -l |
-c or --color |
Interpret ANSI color and style sequences | watch -c 'ls --color=always' |
Practical Application Examples
Monitor system memory usage
watch -n 1 free -h
This command refreshes once per second to show current memory usage (-h option makes the output easier to read).
Monitor directory file changes
watch -d 'ls -l /var/log'
Use -d option highlights changes in the file list, making it ideal for monitoring log directories.
Monitor network connections
watch -n 0.5 'netstat -tulnp | grep 80'
This command checks network connections on port 80 every 0.5 seconds.
Monitor CPU temperature
watch -n 2 'sensors | grep Core'
Display CPU core temperature every 2 seconds.
Advanced Tips
Combining multiple commands
watch 'date; echo; df -h'
Use semicolons to separate multiple commands,echo which adds blank lines to separate the output.
Monitor a specific user's processes
watch 'ps -u username -o pid,cmd,%cpu,%mem --sort=-%cpu'
Monitor processes of a specified user, sorted by CPU usage.
Using pipes and redirection
watch 'dmesg | tail -20 > /tmp/dmesg.log; cat /tmp/dmesg.log'
Although watch cannot handle pipes directly, it can be done through temporary files.
Notes
- Exiting watch: press
Ctrl+Cexits the watch command - Refresh frequency: setting too short an interval (such as 0.1 seconds) may cause high system load
- Command length: overly long commands may affect readability; consider using a script instead
- Color support: some commands need extra parameters to keep color output, such as
ls --color=always
Alternative comparison
| Tool | Feature | Applicable scenarios |
|---|---|---|
| watch | Simple and easy to use, full-screen refresh | Need to continuously monitor command output |
| tail -f | Track file changes in real time | Monitor log file growth |
| tmux + loop commands | More flexible, supports multiple windows | Complex monitoring needs |
| htop | Interactive system monitoring | System resource monitoring |
Linux Command Reference