Objective: Execute a program on the shell every x seconds, display the program output and highlight the changes to the output.
To execute a program at regular intervals, you can schedule it using cron or by using a simple loop.
1 |
$ while true; do /path/to/program ; sleep 60; done |
The above loop will run a process called program every 60 seconds.
But there is another easier way of achieving this – by using the watch Linux command. The watch command is much more flexible and it can be used to highlight differences in output, send a beep if the executed command has a non-zero output, or exit when the output changes.
To check the memory usage every second, use the following syntax.
1 |
$ watch -n 1 free -m |
To run a program every 5 seconds and to exit when the output changes, use the following syntax. This can be used to monitor changes to the command output.
1 |
$ watch -n 5 -g /path/to/program |
To run a program every 5 seconds and to highlight the differences between program output, use the following syntax.
1 |
$ watch -n 5 -d /path/to/program |
To exit the watch command, use Ctrl-C
.
If you are copying a very large file, you can also use the watch command to monitor the copy progress by checking the file size of the file being copied.
1 2 |
$ cp ubuntu-16.04-server-amd64.iso /backup & $ watch -n 1 du -hs /backup/ubuntu-16.04-server-amd64.iso |
Once you run the above command, you will get a screen something like the one below. The file size will be updated every 0.1 second.
1 2 3 |
Every 0.1s: du -hs /backup/ubuntu-16.04-server-amd64.iso 100M /backup/ubuntu-16.04-server-amd64.iso |