Linux Command Repeating

LinuxLinuxBeginner
Practice Now

Introduction

The watch command is a powerful utility in Linux systems that allows users to execute a command periodically and display its output on the terminal. This tool is particularly useful for monitoring system resources, tracking file changes, or observing any process that produces output at regular intervals.

In this lab, you will learn how to use the watch command to automate repetitive tasks and monitor system changes. You will understand its syntax, options, and practical applications in real-world scenarios. By the end of this lab, you will be able to set up automated monitoring processes to observe changes in your system efficiently.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL linux(("Linux")) -.-> linux/TextProcessingGroup(["Text Processing"]) linux(("Linux")) -.-> linux/SystemInformationandMonitoringGroup(["System Information and Monitoring"]) linux(("Linux")) -.-> linux/VersionControlandTextEditorsGroup(["Version Control and Text Editors"]) linux(("Linux")) -.-> linux/BasicFileOperationsGroup(["Basic File Operations"]) linux(("Linux")) -.-> linux/FileandDirectoryManagementGroup(["File and Directory Management"]) linux/BasicFileOperationsGroup -.-> linux/ls("Content Listing") linux/BasicFileOperationsGroup -.-> linux/cat("File Concatenating") linux/BasicFileOperationsGroup -.-> linux/chmod("Permission Modifying") linux/FileandDirectoryManagementGroup -.-> linux/cd("Directory Changing") linux/TextProcessingGroup -.-> linux/grep("Pattern Searching") linux/SystemInformationandMonitoringGroup -.-> linux/watch("Command Repeating") linux/SystemInformationandMonitoringGroup -.-> linux/free("Memory Reporting") linux/VersionControlandTextEditorsGroup -.-> linux/nano("Simple Text Editing") subgraph Lab Skills linux/ls -.-> lab-271435{{"Linux Command Repeating"}} linux/cat -.-> lab-271435{{"Linux Command Repeating"}} linux/chmod -.-> lab-271435{{"Linux Command Repeating"}} linux/cd -.-> lab-271435{{"Linux Command Repeating"}} linux/grep -.-> lab-271435{{"Linux Command Repeating"}} linux/watch -.-> lab-271435{{"Linux Command Repeating"}} linux/free -.-> lab-271435{{"Linux Command Repeating"}} linux/nano -.-> lab-271435{{"Linux Command Repeating"}} end

Understanding the Watch Command Basics

The watch command allows you to run another command repeatedly at specified intervals. This is useful when you need to monitor a changing situation or observe the output of a command over time.

Let's start by exploring the basic syntax of the watch command:

watch [options] command

Common options include:

  • -n <seconds>: Specify the update interval in seconds (default is 2 seconds)
  • -d: Highlight changes between updates
  • -t: Turn off the header showing the command and current time

Let's create a simple example to demonstrate how watch works. First, navigate to your working directory:

cd ~/project

Now, let's create a simple script that generates a random number each time it runs. This will help us visualize how watch repeats commands. Create a file called generate_number.sh with the following content:

nano ~/project/generate_number.sh

In the nano editor, type the following content:

#!/bin/bash
echo "Random number: $((RANDOM % 100 + 1))" > ~/project/number.txt
cat ~/project/number.txt

Press Ctrl+O followed by Enter to save the file, then Ctrl+X to exit nano.

Now make the script executable:

chmod +x ~/project/generate_number.sh

Let's run the script once to see what it does:

~/project/generate_number.sh

The output should show a random number between 1 and 100.

Now, let's use the watch command to run this script every 3 seconds:

watch -n 3 ~/project/generate_number.sh

You will see the command output refreshing every 3 seconds, displaying a new random number each time. The header at the top shows the command being executed and the current time.

To exit the watch command, press Ctrl+C.

Let's try another example with the -d option to highlight changes:

watch -n 3 -d ~/project/generate_number.sh

Notice how the changes in the output are highlighted between updates. This is especially useful when monitoring large outputs and you need to quickly identify what has changed.

Monitoring System Resources with Watch

One of the most common uses of the watch command is monitoring system resources. In this step, you will learn how to use watch to monitor some basic system information.

Let's start by monitoring the memory usage of your system using the free command:

watch -n 2 free -m

The above command will display the memory usage in megabytes (-m) and refresh the output every 2 seconds. This is useful for monitoring memory consumption over time.

Press Ctrl+C to exit the watch command.

Now, let's monitor the disk usage:

watch -n 5 df -h

This command shows the disk usage in human-readable format (-h) and updates every 5 seconds. You can see the available and used space on different partitions of your system.

Press Ctrl+C to exit the watch command.

Let's explore another useful application by monitoring the running processes on your system:

watch -n 3 "ps aux | head -10"

This command displays the top 10 processes sorted by CPU usage and updates every 3 seconds. Notice that we enclosed the complex command in quotes to make it work correctly with watch.

Press Ctrl+C to exit the watch command.

Let's create a specific directory to monitor file changes:

mkdir -p ~/project/monitor_dir
touch ~/project/monitor_dir/file1.txt

Now, let's use watch to monitor the directory for any changes:

watch -n 2 "ls -l ~/project/monitor_dir"

Keep this command running in your terminal. Now, open a new terminal and create a new file in the monitored directory:

touch ~/project/monitor_dir/file2.txt

Observe how the watch command in the first terminal automatically updates to show the new file. This demonstrates how watch can be used to monitor directory changes in real-time.

Press Ctrl+C in the first terminal to exit the watch command.

Advanced Watch Command Features

In this step, you will learn about some advanced features of the watch command that can make your monitoring tasks more efficient.

Let's start by exploring the -t option, which turns off the header showing the command and current time:

watch -n 3 -t date

Notice that the header is now hidden, giving a cleaner display focused only on the command output. This is useful when you want to maximize screen space for the output.

Press Ctrl+C to exit.

Next, let's look at how to use watch with the -g or --chgexit option. This option makes watch exit when the output of the command changes:

touch ~/project/test_change.txt
watch -g -n 1 "ls -l ~/project/test_change.txt"

While this command is running, open a new terminal and modify the file:

echo "hello" > ~/project/test_change.txt

The watch command in the first terminal should exit automatically when it detects the change in the file.

Let's create a more practical example. We'll create a script that simulates a log file with occasional errors:

nano ~/project/simulate_logs.sh

In the nano editor, type the following content:

#!/bin/bash
LOG_FILE=~/project/application.log

## Initialize log file
echo "Starting log simulation" > $LOG_FILE

## Generate simulated log entries
for i in {1..10}; do
  echo "[$(date)] - INFO: Normal operation $i" >> $LOG_FILE
  sleep 1

  ## Occasionally generate an error
  if ((i % 3 == 0)); then
    echo "[$(date)] - ERROR: Something went wrong!" >> $LOG_FILE
  fi
done

echo "Log simulation complete" >> $LOG_FILE

Save and exit nano (Ctrl+O, Enter, Ctrl+X), then make the script executable:

chmod +x ~/project/simulate_logs.sh

Now, let's use watch with grep to monitor for error messages in the log file:

watch -n 1 "grep ERROR ~/project/application.log || echo 'No errors found'"

In another terminal, run the log simulation script:

~/project/simulate_logs.sh

Watch how the first terminal displays when error messages appear in the log file. This is a practical example of using watch for monitoring logs in real-time.

Press Ctrl+C to exit the watch command.

Finally, let's see how to run watch in the background and redirect its output to a file:

watch -n 5 date > ~/project/date_output.txt 2>&1 &

This command runs the watch command in the background, updating the date every 5 seconds and saving the output to a file. You can check the file content:

cat ~/project/date_output.txt

To stop the background watch process, find its PID and kill it:

ps aux | grep "watch -n 5 date"
kill <PID>  ## Replace <PID> with the actual process ID number

These examples demonstrate the versatility of the watch command for various monitoring tasks.

Summary

In this lab, you have learned how to use the watch command in Linux to execute commands repeatedly at specified intervals. This powerful utility can be used for various monitoring tasks, making it an essential tool for system administrators and Linux users alike.

Key concepts covered in this lab:

  1. Basic usage of the watch command with various options like -n to specify the interval and -d to highlight changes.
  2. Monitoring system resources such as memory usage, disk space, and running processes using watch combined with commands like free, df, and ps.
  3. Using watch to monitor file and directory changes in real-time.
  4. Advanced features of watch including running without headers (-t), exiting on change detection (-g), and combining with other commands for specific monitoring needs.
  5. Running watch in the background and redirecting its output to files.

The watch command is a versatile tool that can save you time and effort when you need to monitor changing situations or automatically refresh command outputs. Its ability to work with any command that produces terminal output makes it adaptable to a wide range of scenarios, from system administration to application development and debugging.