巧用watch命令执行循环操作,来解放我们的双手

  • 来源:网络
  • 更新日期:2020-08-07

摘要:建站服务器 有时候我们需要重复执行某个 命令 ,观察某个文件和某个结果的变化情况。可以写 脚本 去实现这些需求,但是有更简单的方法

建站服务器

有时候我们需要重复执行某个 命令 ,观察某个文件和某个结果的变化情况。可以写 脚本 去实现这些需求,但是有更简单的方法,本文档要介绍的就是watch 命令 。

1. 以固定时间反复执行某个命令

root@jaking-virtual-machine:~# watch -n 1 cat hello.txt

Every 1.0s: cat hello.txt                                                                   

jaking-virtual-machine: Tue Mar 19 19:13:33 2019

Hello World!

Hello Jaking!

2. 高亮变化内容

root@jaking-virtual-machine:~# watch -d uptime  #为了突出变化部分,可以使用 -d(difference)参数。

Every 2.0s: uptime                                                                         

jaking-virtual-machine: Tue Mar 19 19:14:01 2019

19:14:01 up 3 days, 12:53,  2 users,  load average: 0.01, 0.01, 0.00

(这里省略,变化内容会高亮,非常便于观察)

3. 执行出错时退出

root@jaking-virtual-machine:~# watch -n 1 -e cat hello.txt    #运行某个命令,当退出码不是0时,即命令执行出错时就结束,可以使用 -e(errexit)参数。

Every 1.0s: cat hello.txt                                                                 

jaking-virtual-machine: Tue Mar 19 19:16:49 2019

打开另一个终端,执行mv操作,可以看到效果:

root@jaking-virtual-machine:~# mv hello.txt /tmp

#新终端

root@jaking-virtual-machine:~# watch -n 1 -e cat hello.txt

#旧终端

Every 1.0s: cat hello.txt                                                                 

jaking-virtual-machine: Tue Mar 19 19:16:49 2019

cat: hello.txt: No such file or directory

4. 执行结果变化时退出

root@jaking-virtual-machine:~# watch -n 1 -g 'du -b hello.txt'                                                                           

Every 1.0s: du -b hello.txt                                                               

jaking-virtual-machine: Tue Mar 19 19:23:41 2019

27      hello.txt

打开另一个终端执行echo操作,可以看到效果:

root@jaking-virtual-machine:~# echo "watch -n -l -g command" >> hello.txt

#新终端

root@jaking-virtual-machine:~# watch -n 1 -g 'du -b hello.txt' 

#旧终端                                                                         

Every 1.0s: du -b hello.txt                                                               

jaking-virtual-machine: Tue Mar 19 19:21:55 2019

50      hello.txt

#此时watch -n 1 -g 'du -b hello.txt'运行结束

root@jaking-virtual-machine:~#


新网虚拟主机