Linux之watch命令
最近项目中有这么个需求: 需要定时监测嵌入式设备中内存变化情况
后面了解到Linux的watch命令可以实时
监测命令的运行结果
1. watch命令
watch usage:
直接在 watch 后面接你想运行的命令,watch 就会帮你周期性运行,并把每次的结果都更新在屏幕上。
默认 watch 会以 2s 的间隔重复运行。
watch runs command repeatedly, displaying its output and errors (the first screenfull). This allows you to watch the program output change over time. By default, the program is
run every 2 seconds. By default, watch will run until interrupted.
OPTIONS
-d, --differences [permanent]
Highlight the differences between successive updates. Option will read optional argument that changes highlight to be permanent, allowing to see what has changed at least
once since first iteration.
-n, --interval seconds
Specify update interval. The command will not allow quicker than 0.1 second interval, in which the smaller values are converted.
-p, --precise
Make watch attempt to run command every interval seconds. Try it with ntptime and notice how the fractional seconds stays (nearly) the same, as opposed to normal mode where
they continuously increase.
-t, --no-title
Turn off the header showing the interval, command, and current time at the top of the display, as well as the following blank line.
-b, --beep
Beep if command has a non-zero exit.
-e, --errexit
Freeze updates on command error, and exit after a key press.
-g, --chgexit
Exit when the output of command changes.
-c, --color
Interpret ANSI color and style sequences.
-x, --exec
command is given to sh -c which means that you may need to use extra quoting to get the desired effect. This with the --exec option, which passes the command to exec(2)
instead.
-h, --help
Display help text and exit.
-v, --version
Display version information and exit.
常用的几个命令选项:
-d , 高亮显示变化的区域
-n, 指定时间间隔
-t或-no-title, 会关闭watch 命令在顶部的时间间隔命令
2. watch的实例用法
每隔一秒高亮显示http链接数的变化情况
命令:
watch -n 1 -d 'pstree|grep http'
说明:
每隔一秒高亮显示http链接数的变化情况。 后面接的命令若带有管道符,需要将命令放在’'中
10秒一次输出系统的平均负载
命令:
watch -n 10 'cat /proc/loadavg'
10秒一次输出系统的内存使用情况
watch -n 10 -d 'free -m'