watch解放你的双手

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

猜你喜欢

转载自www.cnblogs.com/linuxprobe-sarah/p/10619321.html