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. 高亮變化內容it

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. 執行出錯時退出table

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操做,能夠看到效果:file

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操做,能夠看到效果:command

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:~#
相關文章
相關標籤/搜索