Linux系统之watch命令的基本使用
一、watch命令介绍
二、watch命令的使用帮助
2.1 watch命令的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).
2.2 watch命令的语法解释
- 语法
watch(选项)(参数)
- 选项
-n或--interval:指定执行命令的间隔时间,默认为2秒;
-d或--differences:高亮显示变化的部分;
-t或--no-title:不在顶部显示标题栏,仅显示命令输出结果;
-p或--precise:使用最精确的输出,每秒输出一次;
-c或--color:使用彩色输出。
-h或--help:显示帮助信息。
- 参数
指令:需要周期性执行的指令。
三、watch命令的基本使用
3.1 使用默认的2秒时间间隔执行ls命令
watch ls
3.2 每隔10秒执行一次ps命令
watch -n 10 ps
3.3 每隔1秒输出一次磁盘使用情况
watch -n 1 df -h
3.4 高亮显示grep命令的输出
watch -d grep "error" /var/log/messages
3.5 仅输出命令结果
watch -t date
四、watch命令的日常使用场景
4.1 监控目录下的文件变化
watch -n 5 ls
watch -d -n 5 ls
4.2 监控文件内容的变化
echo "hello" >> myweb.txt
watch -d -n 5 cat myweb.txt
4.3 监控内存的变化
watch -d -c -n 1 free -m
4.4 监控系统负载情况
watch -d -c -n 1 uptime
4.5 监控httpd服务状态
watch -d -c -n 1 'ss -tunlp |grep 80'
五、watch命令的使用注意事项
- watch命令的输出结果由终端宽度限制,如果输出结果过长可能会被截断;
- 如果命令执行时间较长,可能会导致watch命令的输出结果不太准确,甚至会出现一些异常行为;
- watch命令不能用于交互式命令,如vi等。