How to monitor any command output in real-time with watch command on Linux

How to monitor any command output in real-time with watch command on Linux

On Linux, watch command helps you refresh the output of a command every second, which functions just like a real-time monitoring. Let’s look at some practical examples.

Monitor log output

One of the most common scenarios in Linux is looking at the log output of an application using the tail command

$ tail -n 10 output.log

This command will output the last 10 lines of the output.log file to the terminal console.

Let’s say you want to check if there is anything new appended to the log file, you will have to re-run the command every time. To do this automatically, just add a watch command at the beginning of the previous command like this

$ watch tail -n 10 output.log

By default, watch command refresh every 2 seconds. If you want to change the interval, add a -n argument like this

$ watch -n 1 tail -n 10 output.log

This will make the command refresh every 1 second, showing the last 10 lines of the log file.

Monitor disk I/O status

You can monitor disk I/O with iostat command.

First, you have to install iostat, which is included in sysstat package

On CentOS

$ yum install sysstat

On Ubuntu

$ apt install sysstat

Then run the command

$ iostat

Monitor I/O status in real-time

$ watch iostat

Monitor network connection

Let’s say you are running a web server on port 80 and want to check how many clients are connecting to the server.

First, we list all connection to the server using netstat command

$ netstat -naltp

Then we filter those connections to port 80 that are established

$ netstat -naltp | grep :80 | grep ESTABLISHED

If you want to count the connections, add a -c argument

$ netstat -naltp | grep :80 | grep ESTABLISHED -c

To refresh the command in real-time, add watch at the beginning

$ watch "netstat -naltp | grep :80 | grep ESTABLISHED -c"

Notice that in the command above, the command to be watched is wrapped inside quotes. This is because without the quotes, the grep command is confused which output stream to consume: watch command or netstat command. To clear out the confusion, we have to put the command we want to “watch” in quotes

Monitor disk usage and disk free space

To monitor disk free space

$ watch df -h

To monitor disk usage

$ watch du -c -h -d 1

Monitor how many instances of a process is running

To monitor how many instances of a process is running, use a ps command with watch

$ watch "ps aux | grep nginx - c"

Leave a Reply

Be the First to Comment!

Notify of
wpDiscuz