System Monitoring with ‘Watch’ | Linux Command Guide

System Monitoring with ‘Watch’ | Linux Command Guide

Graphic depiction of a Linux terminal with the watch command for repeatedly running a command at intervals

Ever felt like you’re wrestling with the ‘watch’ command in Linux? You’re not alone. Many developers find the watch command a bit challenging to master. But, it may help to think of the watch command in Linux as a vigilant guard – it allows you to monitor changes to your system in real-time and keep an eye on your system’s activities and changes.

In this guide, we’ll walk you through the ins and outs of the watch command in Linux, from basic usage to advanced techniques. We’ll cover everything from running simple commands repeatedly, monitoring file system changes, to using it with different flags or options. So, let’s dive in and start mastering the watch command in Linux!

TL;DR: How Do I Use the Watch Command in Linux?

The watch command in Linux is used to run a command repeatedly and display the results on the terminal. It is used with the synax, watch [options] command It’s a powerful tool that can help you monitor changes in your system in real-time.

Here’s a simple example:

watch df -h

# Output:
# Filesystem      Size  Used Avail Use% Mounted on
# udev            3.9G     0  3.9G   0% /dev
# tmpfs           788M  1.9M  786M   1% /run
# /dev/sda1        30G  5.8G   23G  21% /

In this example, the watch command is used to run the df -h command every 2 seconds (default interval). The df -h command displays disk usage in a human-readable format. So, with the help of the watch command, you can monitor your disk usage in real-time.

This is just a basic way to use the watch command in Linux, but there’s much more to learn about this powerful tool. Continue reading for more detailed information and advanced usage scenarios.

Basic Use of the Watch Command in Linux

The watch command in Linux is a powerful tool that can run a command repeatedly and display the results on the terminal. This comes in handy when you want to monitor changes in your system in real-time.

Let’s dive into a basic example of using the watch command. Suppose you want to monitor the changes in the list of logged-in users on your system. You can achieve this by using the who command with watch.

watch who

# Output (will change as users log in and out):
# john    pts/0        2021-10-01 14:04 (192.168.1.2)
# mary    pts/1        2021-10-01 14:05 (192.168.1.3)

In this example, the watch command is used to run the who command every 2 seconds (default interval). The who command displays a list of logged-in users. So, with the help of the watch command, you can monitor your system’s logged-in users in real-time.

The watch command is simple to use and can be incredibly helpful in many situations. However, it’s worth noting that it’s not without its pitfalls. For instance, the command will keep running until you manually stop it (using Ctrl+C), which might not be ideal in some situations. But don’t worry, as we move on to the more advanced uses, you will learn how to overcome this and other potential challenges.

Advanced Usage of the Watch Command in Linux

As you become more comfortable with the basic usage of the watch command, you’ll find that its true power lies in its advanced features. The watch command’s flexibility allows it to handle more complex system monitoring tasks, such as using different flags or options. Let’s explore some of these advanced uses.

Before we dive into the advanced usage of the watch command, let’s familiarize ourselves with some of the command-line arguments or flags that can modify the behavior of the watch command. Here’s a table with some of the most commonly used watch command arguments.

ArgumentDescriptionExample
-nChanges the interval between command executions.watch -n 1 df -h
-dHighlights the differences between successive updates.watch -d ls -l
-tTurns off the header showing the interval, command, and current time.watch -t date
-bExecutes command in the background.watch -b df -h
-eExits if the command returns a non-zero exit code.watch -e ls -l
-gExits when the output of command changes.watch -g date
-xPasses command to exec instead of “sh -c”.watch -x ls -l

Now that we have a basic understanding of watch command line arguments, let’s dive deeper into the advanced use of the watch command.

Monitoring Disk Space Usage in Real-Time

One common use of the watch command is to monitor disk space usage in real-time. This can be particularly useful if you are running processes that you expect to consume a lot of disk space and you want to keep an eye on it.

watch -n 1 df -h

# Output (will change as disk space usage changes):
# Filesystem      Size  Used Avail Use% Mounted on
# udev            3.9G     0  3.9G   0% /dev
# tmpfs           788M  1.9M  786M   1% /run
# /dev/sda1        30G  5.8G   23G  21% /

In this example, the -n 1 argument changes the interval between command executions to 1 second, allowing for near real-time monitoring of disk space usage.

Highlighting Differences Between Successive Updates

Another advanced use of the watch command is to highlight the differences between successive updates. This can be particularly useful when you are monitoring changes to a file or directory.

watch -d ls -l

# Output (changes will be highlighted):
# total 12
# drwxr-xr-x 2 root root 4096 Oct  1 14:05 dir1
# -rw-r--r-- 1 root root   30 Oct  1 14:05 file1

In this example, the -d argument highlights the differences between successive updates, making it easier to spot changes.

Running the Watch Command in the Background

You can also run the watch command in the background using the -b argument. This can be particularly useful if you want to continue using the terminal while the watch command runs in the background.

watch -b df -h

# Output:
# [1] 12345

In this example, the -b argument runs the watch command in the background, and the process ID of the background process is displayed.

These are just a few examples of the advanced uses of the watch command in Linux. The watch command is a powerful tool that can be used in a variety of ways to monitor your system in real-time.

Alternative Techniques to the Watch Command in Linux

While the watch command is a powerful tool for monitoring changes in real-time, there are alternative methods and commands in Linux that can accomplish similar tasks. Understanding these alternatives can provide you with more flexibility and options when it comes to system monitoring.

Using the Cron Job for Scheduled Monitoring

Cron is a time-based job scheduling service in Unix-like operating systems. Users can schedule jobs (commands or scripts) to run periodically at fixed times, dates, or intervals. If you need to monitor changes less frequently or at specific times, using a cron job might be a better choice.

Here’s an example of a cron job that checks disk usage every hour and writes the output to a log file:

# Edit the crontab file

crontab -e

# Add the following line to the crontab file

0 * * * * df -h > /home/user/disk_usage.log

# Output in disk_usage.log:
# Filesystem      Size  Used Avail Use% Mounted on
# udev            3.9G     0  3.9G   0% /dev
# tmpfs           788M  1.9M  786M   1% /run
# /dev/sda1        30G  5.8G   23G  21% /

In this example, the df -h command is scheduled to run at the start of every hour. The output is redirected to a log file for later review.

Using the inotify Tools for File System Event Monitoring

The inotify tools provide a method for monitoring file system events such as modifications, accesses, openings, and closings. If your monitoring needs are more file-centric, the inotify tools might be a better fit.

Here’s an example of using the inotifywait command to monitor changes to a directory:

# Install inotify-tools

sudo apt install inotify-tools

# Monitor changes to a directory

inotifywait -m /path/to/directory

# Output (will change as file system events occur):
# /path/to/directory/ OPEN file1
# /path/to/directory/ CLOSE_WRITE,CLOSE file1

In this example, the inotifywait -m /path/to/directory command monitors the specified directory for file system events and prints them to the console.

These are just a few examples of the alternative methods to the watch command in Linux. Each method has its benefits and drawbacks, and the best choice depends on your specific needs and circumstances.

Troubleshooting the Watch Command in Linux

Like any command in Linux, the watch command can sometimes throw up errors or obstacles that can be a bit tricky to navigate. Let’s look at some common issues you might encounter when using the watch command and how to solve them.

Issue 1: Command Not Found

If you’re new to Linux, you might encounter the ‘command not found’ error when trying to use the watch command. This is usually because the procps package, which provides the watch command, is not installed on your system.

watch df -h

# Output:
# bash: watch: command not found

In this case, you can install the procps package using your system’s package manager. For Debian-based systems like Ubuntu, you can use the apt package manager.

sudo apt install procps

After the installation is complete, you should be able to use the watch command without any issues.

Issue 2: Watch Command Doesn’t Stop

Another common issue with the watch command is that it doesn’t stop running until you manually stop it (using Ctrl+C). While this is actually a feature of the watch command, it can be a problem if you accidentally leave a watch command running in the background.

To solve this, you can use the timeout command to limit the execution time of the watch command.

timeout 10 watch df -h

# Output:
# Every 2.0s: df -h
# Filesystem      Size  Used Avail Use% Mounted on
# udev            3.9G     0  3.9G   0% /dev
# tmpfs           788M  1.9M  786M   1% /run
# /dev/sda1        30G  5.8G   23G  21% /

In this example, the timeout 10 command limits the execution time of the watch df -h command to 10 seconds.

Issue 3: Watch Command Doesn’t Show Changes

Sometimes, the watch command might not show changes as expected. This can happen if the command you’re running with watch doesn’t produce different output on successive runs.

To solve this, you can use the -d flag to highlight the differences between successive updates.

watch -d ls -l

# Output (changes will be highlighted):
# total 12
# drwxr-xr-x 2 root root 4096 Oct  1 14:05 dir1
# -rw-r--r-- 1 root root   30 Oct  1 14:05 file1

In this example, the -d flag highlights the differences between successive updates, making it easier to spot changes.

These are just a few examples of the issues you might encounter when using the watch command in Linux. With a bit of practice and troubleshooting, you’ll be able to use the watch command effectively to monitor your system in real-time.

Understanding the Watch Command in Linux

The watch command in Linux is a part of the broader Linux command line environment, and understanding its fundamentals can provide a deeper insight into its workings and potential applications.

The Anatomy of the Watch Command

At its core, the watch command executes a program or command periodically, showing its output and errors (the first screenfull). This allows you to watch the program output change over time. By default, the specified program or command is run every 2 seconds.

Here’s a basic structure of the watch command:

watch [options] command

In this structure, [options] are the command line options such as -n (to specify the interval in seconds), -d (to highlight the differences between successive updates), and command is the command you want to run.

The Watch Command and the Linux Command Line Environment

The watch command is a part of the Linux command line environment, which is a powerful and flexible way to interact with a Linux system. The Linux command line provides a wide range of commands and utilities that can manipulate the system and its files, and the watch command is one of them.

The watch command is particularly useful for system administration tasks where you need to monitor changes to the system in real-time. For example, you can use the watch command to monitor the CPU usage, memory usage, disk usage, network traffic, and more.

Let’s take a look at an example where the watch command is used to monitor the CPU usage in real-time:

watch -n 1 'ps -eo pcpu,pid,user,args | sort -k 1 -r | head -10'

# Output (will change as CPU usage changes):
# %CPU   PID USER     COMMAND
#  0.7  1234 user     /usr/bin/python /usr/bin/indicator-cpufreq
#  0.3  5678 user     /usr/lib/unity/unity-panel-service
#  0.2  9101 user     /usr/bin/X :0 -seat seat0 -auth /var/run/lightdm/root/:0 -nolisten tcp vt7 -novtswitch

In this example, the watch -n 1 'ps -eo pcpu,pid,user,args | sort -k 1 -r | head -10' command monitors the top 10 processes with the highest CPU usage in real-time. The -n 1 option updates the output every second.

The watch command is a powerful tool in the Linux command line environment, and understanding its fundamentals can help you use it more effectively to monitor your system in real-time.

Beyond Basic Usage: The Watch Command in Larger Scripts and Projects

The watch command in Linux is not only useful for monitoring system changes in real-time, but it can also play a significant role in larger scripts or projects. Its ability to repeatedly execute a command and display its output can be leveraged in many ways to enhance your scripts or projects.

Integrating the Watch Command into Shell Scripts

You can integrate the watch command into your shell scripts to monitor the output of other commands over time. This can be particularly useful in long-running scripts where you want to keep an eye on the progress.

Here’s an example of a shell script that uses the watch command to monitor the number of lines in a log file:

#!/bin/bash

# Path to the log file
log_file="/path/to/log/file"

# Use the watch command to monitor the number of lines in the log file
watch -n 1 'wc -l $log_file'

# Output (will change as lines are added to the log file):
# 100 /path/to/log/file

In this example, the watch -n 1 'wc -l $log_file' command is used to monitor the number of lines in the log file every second. This can be useful to track the progress of a script that writes to the log file.

Semi-related Commands That Often Accompany the Watch Command

In addition to its standalone use, the watch command is often used in conjunction with other commands to monitor system changes in real-time. Some of these semi-related commands include df (for disk usage), free (for memory usage), top (for CPU usage), netstat (for network statistics), and ps (for process status).

Here’s an example of using the watch command with the netstat command to monitor network connections in real-time:

watch -n 1 'netstat -tuln'

# Output (will change as network connections change):
# Proto Recv-Q Send-Q Local Address           Foreign Address         State
# tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN
# tcp6       0      0 :::22                   :::*                    LISTEN

In this example, the watch -n 1 'netstat -tuln' command is used to monitor network connections every second. This can be useful for detecting unauthorized connections or troubleshooting network issues.

Further Resources for Mastering the Watch Command

To further enhance your understanding and mastery of the watch command in Linux, here are some additional resources:

  1. Watch Command Guide – This is guide by Network World explains the watch command.

  2. Linuxize: Watch Command in Linux – This is a comprehensive guide on the watch command in Linux, including its usage, command options, and examples.

  3. Linux Watch Command Examples – This article provides a detailed explanation of the watch command, along with several practical examples.

Wrapping Up: Watch Command Guide in Linux

In this comprehensive guide, we’ve explored the ins and outs of the watch command in Linux, a powerful tool for monitoring system changes in real-time.

We started off with the basics, learning how to use the watch command in its simplest form. We then delved into more advanced usage, exploring how to use the watch command with different flags or options, and how to integrate it into larger scripts or projects. Along the way, we tackled common issues you might encounter when using the watch command, providing solutions and workarounds for each issue.

We also looked at alternative approaches to the watch command, such as using cron jobs for scheduled monitoring and inotify tools for file system event monitoring. Here’s a quick comparison of these methods:

MethodProsCons
Watch CommandReal-time monitoring, flexibleContinues until manually stopped
Cron JobScheduled monitoring, ideal for less frequent changesNot real-time
Inotify ToolsFile-centric, monitors file system eventsMore complex setup

Whether you’re just starting out with the watch command or you’re looking to level up your Linux command line skills, we hope this guide has given you a deeper understanding of the watch command and its capabilities.

With its ability to monitor system changes in real-time, the watch command is a powerful tool in the Linux command line environment. Now, you’re well equipped to use it effectively in your system monitoring tasks. Happy monitoring!