示例 1:监视动态更改的文件,例如 /proc/meminfo

有一种方法可以使用 watch 命令监视系统上的任何文件。

命令:

# watch -n 10 -d  cat /proc/meminfo

将在屏幕上每 10 秒产生一次 meminfo 状态的输出,并在有任何更改时突出显示。

on  it road.com

示例 3:从输出中删除标题/标题。

如果我们不想在 watch 命令的输出中打印标题,我们可以使用 -no-title 或者 -t 选项。

# watch -t -d ls -lt
total 0
-rw-r--r-- 1 root root 0 Nov 14 10:47 new_file_just_created
-rw-r--r-- 1 root root 0 Nov 14 10:46 file1
-rw-r--r-- 1 root root 0 Nov 14 10:46 file2
-rw-r--r-- 1 root root 0 Nov 14 10:46 file3

示例 4:突出显示累积差异

如果要突出显示输出中的累积差异,可以在命令中使用 -d=cumulative 开关。
例如 :
添加新文件 new_file1 后的输出:

添加另一个新文件 new_file2 后的输出:

示例 2:查找目录内容的更改

watch 命令的另一个出色用途是监视目录的内容,并查看是否添加或者删除了任何新文件。

# watch -d ls -lt

ls 命令中的 -lt 开关在顶部显示最新修改的文件。

使用watch命令示重复运行命令或者监视可动态更改的文件

watch命令是一个非常简洁的工具,在许多情况下都派上用场。
watch 命令可用于定期监视任何文件或者脚本。
默认情况下,它每 2 秒运行一次,并且会一直运行直到被中断。

# watch -h
Usage: watch [-dhntv] [--differences[=cumulative]] [--help] [--interval=[n]] [--no-title] [--version] [command]
  -d, --differences[=cumulative]	highlight changes between updates
		(cumulative means highlighting is cumulative)
  -h, --help				print a summary of the options
  -n, --interval=[seconds]		seconds to wait between updates
  -v, --version				print the version number
  -t, --no-title			turns off showing the header

watch 命令的基本语法是:

# watch [-n seconds] [-d] [command]

其中:

-d flag will highlight the differences between successive updates.
-n flag is to specify the interval. The default value is 2 seconds.

这是一个示例输出:

# watch -n 10 -d ls -lt
Every 10.0s: ls -lt                                             Tue Nov 14 12:27:43 2017
total 0
-rw-r--r-- 1 root root 0 Nov 14 12:27 new_file_just_created
-rw-r--r-- 1 root root 0 Nov 14 10:46 file1
-rw-r--r-- 1 root root 0 Nov 14 10:46 file2
-rw-r--r-- 1 root root 0 Nov 14 10:46 file3

其中:

Every 10.0s : is the time interval to run the watch command. for example:10 seconds.
ls -lt : is the command to be executed every 10 seconds.
Tue Nov 14 12:27:43 2017 : is the current date and time.
日期:2020-09-17 00:14:43 来源:oir作者:oir