How To Repeat A Command Every N Seconds In Linux?

Published August 1, 2024

Problem: Repeating Linux Commands at Intervals

Automating command execution at regular intervals is a common task in Linux systems. This can be useful for monitoring system resources, running periodic tasks, or updating information at set times.

The 'watch' Command: A Simple Solution

Basic Syntax of the 'watch' Command

The 'watch' command in Linux runs commands repeatedly at set intervals. It's a built-in tool that shows the output of a command in full-screen, updating it regularly.

To use the 'watch' command, follow this basic syntax:

watch [options] command

The command you want to repeat goes at the end of the 'watch' command. By default, 'watch' runs the specified command every 2 seconds.

To set a custom time interval between repetitions, use the '-n' option followed by the number of seconds. For example:

watch -n 5 command

This will run the command every 5 seconds.

You can also use decimal values for shorter intervals:

watch -n 0.5 command

This runs the command every half second.

The 'watch' command runs until you stop it manually, usually by pressing Ctrl+C.

Tip: Highlight Changes

To highlight changes between updates, use the '-d' or '--differences' option. This makes it easier to spot what's changing in the command output:

watch -d command

This will highlight any differences in the output between updates, making it easier to track changes over time.

Practical Examples of Using 'watch'

Monitoring File Size Changes

The 'watch' command helps monitor file size changes, useful during file imports or downloads. To track file size changes, use 'watch' with the 'ls' command:

watch -n 5 ls -l filename

This command shows file details, including size, every 5 seconds. It's useful when importing large files and you want to see if the size is increasing.

For monitoring multiple files in a directory, use:

watch -n 5 'ls -l | grep filename'

This displays details of all files with 'filename' in their name, updating every 5 seconds.

Tip: Highlight Changes

Use the -d option with 'watch' to highlight the differences between updates. For example:

watch -d -n 5 ls -l filename

This will highlight any changes in the file details, making it easier to spot modifications.

Observing System Resource Usage

'watch' is also useful for monitoring system resources in real-time. To observe CPU usage, use it with the 'top' command:

watch -n 1 'top -b -n 1 | head -n 5'

This shows the top 5 lines of the 'top' command output, refreshing every second.

For monitoring memory usage, combine 'watch' with the 'free' command:

watch -n 2 free -m

This displays memory usage in megabytes, updating every 2 seconds.

To monitor disk usage, use 'watch' with the 'df' command:

watch -n 10 df -h

This shows disk usage in a readable format, refreshing every 10 seconds.

Customizing 'watch' Output

Highlighting Changes with '--differences'

The '--differences' option in the 'watch' command makes changes more visible in repeated outputs. This option highlights the parts of the output that have changed since the last update.

To use this feature, add the '-d' or '--differences' flag to your 'watch' command:

watch -d command

This is useful when monitoring small changes in large outputs. For example, when watching system processes:

watch -d 'ps aux | sort -nrk 3,3 | head -n 5'

This command shows the top 5 CPU-consuming processes and highlights any changes in updates.

Tip: Enhancing Readability with Color

Use the '--color' option along with '--differences' to make changes even more noticeable. For example:

watch -d --color 'df -h'

This command will show disk usage information and highlight changes in color, making it easier to spot modifications in disk space usage over time.

Using the '--cumulative' Option

The '--cumulative' option in 'watch' provides cumulative highlighting, which means it keeps track of all changes over time, not just the most recent ones.

To use this option, add '--cumulative' to your 'watch' command:

watch --cumulative command

This feature is useful for tracking all changes that have occurred since you started watching. For instance, when monitoring log files:

watch --cumulative 'tail -n 10 /var/log/syslog'

This command shows the last 10 lines of the system log and highlights all new entries that have appeared since you started watching.

The '--cumulative' option helps in scenarios where you need to keep track of all changes over a long period, rather than just the most recent ones.

Alternative Methods for Command Repetition

Using Bash Loops

Bash loops are another way to repeat commands in Linux. You can create a loop to run a command multiple times:

while true; do
    command
    sleep 5
done

This loop runs the command every 5 seconds until you stop it manually (usually with Ctrl+C).

Pros of using bash loops:

  • More flexible for complex command sequences
  • Can be modified for different intervals or conditions
  • Works in all shell environments

Cons compared to 'watch':

  • Doesn't provide automatic output refreshing
  • Requires more setup
  • May be less efficient for simple, single-command repetitions

Tip: Customizing Loop Behavior

You can add conditional statements within the loop to control its behavior. For example:

count=0
while [ $count -lt 10 ]; do
    command
    sleep 5
    ((count++))
done

This loop will run the command 10 times before stopping.

Cron Jobs for Scheduled Repetitions

Cron jobs are useful for scheduling commands to run at specific times or intervals, especially for longer periods:

To set up a cron job, edit the crontab file:

crontab -e

Then add a line like this to run a command every 30 minutes:

*/30 * * * * /path/to/your/command

Cron is better than 'watch' when:

  • You need to run commands at specific times
  • The interval between repetitions is long (hours, days, weeks)
  • You want the command to run in the background
  • You need to keep the command running even after logging out

However, 'watch' is more suitable for:

  • Real-time monitoring with shorter intervals
  • Interactive sessions where you need to see output immediately
  • Temporary command repetition during a single session

Bash loops and cron jobs provide alternatives to 'watch' for repeating commands, each with its own strengths depending on the specific use case.