linux watch命令解析与示例

来源:互联网 发布:网络机顶盒一般多少钱 编辑:程序博客网 时间:2024/06/04 20:09

功能概述

  watch - 定时的执行一个程序并将结果全屏显示到输出;默认watch会以2s的间隔重复运行命令,你也可以用 -n 参数指定时间间隔;还有一个实用的参数是-d,这样watch会帮你高亮显示变化的区域  Ctrl+c 就可以退出watch监控  使用场景比如操作日志变化的实时监测(文件内容)、查看变动文件等

用法摘要

   watch [-bdehpvtx] [-n seconds] [--beep] [--color] [--differences[=cumu‐   lative]] [--errexit] [--exec] [--help] [--interval=seconds]   [--no-title] [--precise] [--version] command

-b, –beep
#如果命令有非零的返回码则产生哔哔声

-d, –differences[=cumulative]
#高亮显示变化的内容

-e, –errexit
# 如果命令有非零的返回码则退出监控

-h, –help
#显示帮助信息

-n, –interval=
#设置监控的时间间隔(以秒计算)

-p, –precise
#精确计时,忽略命令运行时间

-v, –version
#输出版本号码

-t, –no-title
#关闭头部显示

-x, –exec
#将命令传递给exec而不是执行

示例及解释

  • 1.监控某个目录的变化
    例如我监控了自己的/home/ubuntu目录,然后修改其下的文件watch.txt,变化的内容就会高亮显示出来
    watch -d -n 1 ‘df; ls -Alt -F /home/ubuntu’
  • 这里写图片描述
  • 2.每隔一秒高亮显示网络链接数的变化情况
    watch -n 1 -d netstat -ant
  • 这里写图片描述
  • 3.每秒一次输出系统的平均负载
    watch -n 10 ‘cat /proc/loadavg’
    这里写图片描述
    -4.监控文件的内容变化(场景为日志监控)
    watch -d -n 1 cat watch.txt
    这里写图片描述
    5.监控你的邮件
    watch -n 60 from
    6.监控特定用户所属的文件
    watch -d ‘ls -l | fgrep joe’