
watch命令是Linux/Unix下一个非常实用的命令,可以用来定期执行一个命令并打印输出结果,可以帮助用户实时监测命令的输出结果,非常适合于需要反复执行某个命令并观察其输出结果的场景。
使用help查询帮助信息
[root@jeven ~]# watch --help
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
For more details see watch(1).
watch(选项)(参数)
-n或--interval:指定执行命令的间隔时间,默认为2秒;
-d或--differences:高亮显示变化的部分;
-t或--no-title:不在顶部显示标题栏,仅显示命令输出结果;
-p或--precise:使用最精确的输出,每秒输出一次;
-c或--color:使用彩色输出。
-h或--help:显示帮助信息。
指令:需要周期性执行的指令。
执行以下命令,使用默认的2秒时间间隔执行ls命令。
watch ls

使用watch的-n命令,每隔10秒执行一次ps命令。
watch -n 10 ps

使用以下命令,每隔1秒输出一次磁盘使用情况。
watch -n 1 df -h

高亮显示grep命令的输出
watch -d grep "error" /var/log/messages

不显示标题栏,仅输出命令结果
watch -t date

执行以下命令,另外再开启一个终端,在当前目录下新建文件,查看监控变化。
watch -n 5 ls

使用-d命令,高亮显示变化部分。
watch -d -n 5 ls

执行以下命令,在另外一个终端,修改文件内容,查看监控中文件内容的变化情况。
echo "hello" >> myweb.txt
watch -d -n 5 cat myweb.txt

使用以下命令,监控内存的变化情况。
watch -d -c -n 1 free -m

使用以下命令,监控系统负载情况。
watch -d -c -n 1 uptime

使用以下命令监听httpd的80端口监听状态
watch -d -c -n 1 'ss -tunlp |grep 80'