How to use the Linux watch command

How to use the Linux watch command

The Linux watch command is a powerful tool that runs user-defined commands at regular intervals and displays the output. It’s important for monitoring processes and system resources in real time without manually re-running commands.

Whether you’re tracking disk usage, monitoring network interfaces, or observing file and directory changes, watch helps streamline these tasks.

In this guide, you’ll learn how to use the watch command, from its basic syntax and options to practical examples. By the end, you’ll be able to efficiently monitor various system activities through the command line.

Prerequisites

To use the watch command, you must access your Linux virtual private server (VPS) or computer using an account with sudo privileges. If you don’t have this permission, grant the sudo access by editing the sudoers file as root.

If you use a remote system, open its command-line interface (CLI) using Terminal or an SSH client application like PuTTY. For desktops, you can open it by pressing Ctrl + Alt + T.

Alternatively, Hostinger VPS users can access their remote server’s CLI via a web browser using the Browser terminal feature.

The Linux watch command syntax

The watch command uses a simple structure, making it easy to set. Here’s its basic syntax:

watch [options] command
  • watch. The main command that will repeat a specified command multiple times at regular intervals.
  • [options]. Optional flags to modify the watch command’s behavior, such as adjusting the interval or highlighting changes.
  • command. The actual Linux command you want to monitor. It can be any command that outputs data to the terminal, such as disk usage, network statistics, or system resources.

When executed, the specified command will continuously refresh its output based on the interval you set. To stop the process, press Ctrl + C.

The watch command options

The watch command offers several options to enhance its functionality. Below are some of the most common ones:

  • -b. Plays a beep sound when the command exits with a non-zero status, indicating an error.
  • -c. Enables ANSI color highlighting in the output.
  • -d. Highlights differences between successive updates, making it easier to spot changes.
  • -e. Evaluates exit status. If watch encounters a command error, it will freeze and quit on a key press.
  • -g. Exits the watch command when the command’s output changes.
  • -h. Shows help information for the watch command.
  • -n [number]. Sets the interval between updates in seconds. The default value is 2.
  • -p. Makes the watch command beep if any output changes.
  • -t. Turns off the header showing the command, update interval, and current time.
  • -w. Toggles line wrapping to truncate long outputs.
  • -x. Executes the command in a shell, allowing you to use more complex commands.
  • –precise. Ensures the interval between updates is consistent by minimizing potential delays.

Examples of the Linux watch command

Now that we’ve discussed the syntax and options, it’s time to look at some real-life watch command examples.

Monitoring system resources

One common use of the watch command is for real-time system monitoring. This can help track CPU usage, memory consumption, and other key metrics to ensure your Linux system is running smoothly.

To monitor CPU and memory usage, combine watch with the top command as shown in the following example:

watch -n 5 top -b -n 1

This watch command updates the system resource usage every five seconds. Here’s the expected output:

top - 15:32:18 up 1:25,  1 user,  load average: 0.16, 0.10, 0.09
Tasks: 203 total,   1 running, 202 sleeping,   0 stopped,   0 zombie
%Cpu(s):  1.7 us,  0.2 sy,  0.0 ni, 98.0 id,  0.0 wa,  0.0 hi,  0.1 si,  0.0 st
MiB Mem :  7977.6 total,  5728.2 free,   766.3 used,  1483.1 buff/cache
MiB Swap:  2048.0 total,  2048.0 free,     0.0 used.  6744.5 avail Mem

Tracking directory changes

You can also use watch to monitor changes in a directory over time. This is particularly helpful for tracking file modifications, additions, or deletions. Combine it with the ls command to track the directory, for instance:

watch -n 10 ls -lh /path/to/directory

watch will update the directory listing every 10 seconds, so you can see changes as they happen. The command output is as follows:

total 20K
-rw-r--r-- 1 user user 1.2K Sep 20 14:32 file1.txt
-rw-r--r-- 1 user user 600 Sep 20 14:34 file2.txt
drwxr-xr-x 2 user user 4.0K Sep 20 14:35 folder1

Monitoring disk usage

Monitoring your Linux system’s disk usage is important to help you detect issues and unused files that can deplete storage space. By using the watch command with df -h, you can periodically monitor how much disk space is currently used.

To monitor disk usage, run the following:

watch -n 15 df -h

The output will display something like this:

Filesystem Size Used Avail Use% Mounted on
/dev/sda1 50G 20G 28G 42% /
/dev/sdb1 100G 60G 35G 64% /mnt/data
tmpfs 1.9G 1.0M 1.9G 1% /dev/shm

Checking network interfaces

Monitoring network interfaces helps track bandwidth usage and identify potential network issues. You can combine watch with either ifconfig or ip -s link to observe real-time network activity changes and detect anomalies.

Here’s an example of checking network interface status using watch and ip -s link:

watch -n 5 ip -s link

After running the command, you should see the output below every five seconds:

1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN mode DEFAULT group default qlen 1000
    RX: bytes  packets  errors  dropped overrun mcast   
         123456  789    0       0       0       0       
    TX: bytes  packets  errors  dropped carrier collsns 
         654321  432    0       0       0       0       
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP mode DEFAULT group default qlen 1000
    RX: bytes  packets  errors  dropped overrun mcast   
         987654  4321   0       0       0       0       
    TX: bytes  packets  errors  dropped carrier collsns 
         123456  5678   0       0       0       0       

Observing log files

Using watch with the tail command lets you observe real-time changes in log files as they add new entries. This is handy when troubleshooting system issues or tracking specific events without manually reopening or refreshing the file.

To observe the updates to a log file, run the following command:

watch -n 20 tail -n 20 /var/log/syslog

This command will display the last 20 lines of the system log file every 20 seconds:

Sep 20 12:35:01 server CRON[12345]: (root) CMD (run-parts /etc/cron.hourly)
Sep 20 12:40:01 server CRON[12346]: (root) CMD (run-parts /etc/cron.daily)
Sep 20 12:45:01 server systemd[1]: Starting Cleanup of Temporary Directories...
Sep 20 12:50:01 server systemd[1]: Started Cleanup of Temporary Directories.

Combining with grep to filter output

The grep command lets you filter another command’s output using keywords. It enables watch to print only the relevant data, minimizing the output for a more efficient analysis.

When using grep, your watch command syntax will change slightly. Since we will use a pipe (|) to pass the output, we must group the commands using quotation marks. Consider the following example:

watch -n 5 "ps aux | grep 'root'"

The snippet monitors new processes, passing it to the grep command to show only new entries containing the word root. The output might look as follows:

root 1 0.0 0.3 169344 13812 ? Ss Sep22 0:18 /sbin/init
root 2 0.0 0.0 0 0 ? S Sep22 0:00 [kthreadd]
root 3 0.0 0.0 0 0 ? I&lt; Sep22 0:00 [rcu_gp]
root 4 0.0 0.0 0 0 ? I&lt; Sep22 0:00 [rcu_par_gp]
root 5 0.0 0.0 0 0 ? I&lt; Sep22  0:00 [slub_flushwq]

Whenever the output of your command changes, grep automatically filters it. This means you will only get a new terminal entry when relevant data registers.

Using watch with custom scripts

In addition to commands, watch lets you repeat script execution. Scripts are useful if you have custom tasks involving multiple utilities and complicated logic. Moreover, scripts are more modular and easily reusable than commands.

To create a bash script, run the following commands. Replace myscript with your desired name:

nano myscript.sh

Write your script logic. For example, let’s make a simple one that prints the current system date and uptime:

#!/bin/bash
echo "Current date and time: $(date)"
echo "Uptime: $(uptime)"

Hit Ctrl + X → Y Enter to save the file. Make the script executable to allow the watch command to run it:

chmod +x myscript.sh

Run the script using the watch command like so. For example, we will set the interval to five seconds:

watch -n 5 ./myscript.sh

The output should look as follows, with the date and uptime updating every five seconds.

Current date and time: Tue Sep 24 06:00:32 AM UTC 2024
Uptime: 06:00:32 up 1 day, 17:50, 1 user, load average: 0.17, 0.09, 0.03

Conclusion

The watch command lets you repeat another command at a specific interval. It makes monitoring real-time data like processes, resource consumption, and logs easier since you don’t need to re-run the command manually to update the output.

To use this utility, enter watch followed by the command you want to repeat. You can also add options to modify its behavior based on your monitoring needs. For example, insert -n to change the execution interval and -g to automatically stop the command when the output changes.

You can use watch with various commands, including top, ls, and ds. Since this utility is versatile, experiment with different combinations to familiarize yourself with the tool and find a suitable use case for your needs.

For Hostinger VPS hosting users, we recommend using Kodee AI Assistant to write the watch command quickly. You can also ask for help if you encounter difficulties using watch for system management.

The Linux watch command FAQ

What is the purpose of the Linux watch command?

Linux watch lets you automatically repeat another user-defined command execution at a specific interval. It is useful for monitoring commands’ outputs without rerunning them manually. For example, you can track new logs, processes, and system resource usage. 

Can the Linux watch command continuously monitor file changes?

Yes, you can check changes in a file using watch by repeating the tail command. It prints the last few lines from a file, allowing you to check if new data exists. 

Can I use the watch command to monitor multiple commands simultaneously?

Yes, you can use watch on multiple commands by listing them inside quotation marks separated by operators. Use the double ampersands (&&) operator to run commands only after the previous one has succeeded. If you want to ignore this rule, use the semicolon separator (;).

Author
The author

Ariffud Muhammad

Ariffud is a Technical Content Writer with an educational background in Informatics. He has extensive expertise in Linux and VPS, authoring over 200 articles on server management and web development. Follow him on LinkedIn.

Author
The Co-author

Aris Sentika

Aris is a Content Writer specializing in Linux and WordPress development. He has a passion for networking, front-end web development, and server administration. By combining his IT and writing experience, Aris creates content that helps people easily understand complex technical topics to start their online journey. Follow him on LinkedIn.