1. 描述

watch 用于周期性地执行指定的命令,并将命令的输出打印到终端上。它可以让您以固定的时间间隔观察命令的输出,非常适合用于监视文件系统、系统状态、日志文件等。

2. 语法

watch 命令的基本语法是:

Usage:
 watch [options] command

Options:
  -b, --beep             beep if command has a non-zero exit
  -c, --color            interpret ANSI color and style sequences
  -d, --differences[=<permanent>]
                         highlight changes between updates
  -e, --errexit          exit if command has a non-zero exit
  -g, --chgexit          exit when output from command changes
  -n, --interval <secs>  seconds to wait between updates
  -p, --precise          attempt run command in precise intervals
  -t, --no-title         turn off header
  -x, --exec             pass command to exec instead of "sh -c"

 -h, --help     display this help and exit
 -v, --version  output version information and exit

其中,command 是要周期性执行的命令。

3. 参数

以下是一些常用的 watch 命令选项:

  • -n, --interval=seconds:指定执行命令的时间间隔,默认为 2 秒。
  • -d, --differences[=cumulative]:高亮显示命令输出的变化部分。
  • -t, --no-title:不显示标题行。
  • -h, --help:显示帮助信息。

4. 例子

每隔1秒查看系统的 CPU 使用情况:

watch -n 1 "top -n 1"

每隔5秒查看系统的磁盘空间情况:

watch -n 5 "df -h"

每隔10秒查看系统日志文件的更新:

watch -n 10 "tail /var/log/syslog"

ps:如果想要在 watch 命令中执行的命令包含空格或其他特殊字符,需要将整个命令用引号括起来!

更多推荐