Skillfully use the watch command to perform loop operations to free our hands
Sometimes we need to execute a command repeatedly to see how a file and a result change. You can write scripts to implement these requirements, but there are simpler ways to do so. This document describes the watch command.
1. Repeat a command for a fixed time
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. Highlight Change Content
root@jaking-virtual-machine:~# watch -d uptime #To highlight changes, use the-d (difference) argument.
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
(Omitted here, the change content will be highlighted, very easy to observe)
3. Exit on execution error
root@jaking-virtual-machine:~# watch -n 1 -e cat hello.txt #Run a command that ends when the exit code is not 0, that is, when the command execution error occurs, you can use the-e (errexit) parameter.
Every 1.0s: cat hello.txt
jaking-virtual-machine: Tue Mar 19 19:16:49 2019
Open another terminal, perform mv operation, you can see the effect:
root@jaking-virtual-machine:~# mv hello.txt /tmp
#new terminal
root@jaking-virtual-machine:~# watch -n 1 -e cat hello.txt
#Old Terminal
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. Exit when execution results change
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
Open another terminal to perform echo operation, you can see the effect:
root@jaking-virtual-machine:~# echo "watch -n -l -g command" >> hello.txt
#new terminal
root@jaking-virtual-machine:~# watch -n 1 -g 'du -b hello.txt'
#Old Terminal
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' ends
root@jaking-virtual-machine:~#