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

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

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

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

Every 1.0s: cat hello.txt                                                                   it

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

Hello World!终端

Hello Jaking!command

2. 高亮变化内容方法

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

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:~#

相关文章
相关标签/搜索