Efficiently Repeating Commands in Bash: Multiple Execution Techniques for Linux Sysadmins


4 views

When administering multiple Linux systems, you often need to repeatedly execute the same command for monitoring or debugging purposes. While writing scripts is ideal for permanent solutions, sometimes you need quick, interactive solutions that work across all machines without custom scripts.

The simplest way to repeat a command is using a for loop:

for i in {1..10}; do ps aux | grep someprocess; done

Alternatively, use a C-style loop when you need the counter variable:

for ((i=0; i<10; i++)); do
    ps aux | grep someprocess
done

For more control over termination conditions:

count=0
while [[ $count -lt 10 ]]; do
    ps aux | grep someprocess
    ((count++))
    sleep 1  # Optional delay between runs
done

Add this to your .bashrc for system-wide availability:

function run() {
    local n=$1
    shift
    for ((i=0; i

Usage example:

run 10 ps aux | grep someprocess

When you need parallel execution (GNU parallel is even better but not always available):

seq 10 | xargs -I{} -P4 sh -c 'ps aux | grep someprocess'

The built-in watch command is perfect for monitoring:

watch -n 1 -d 'ps aux | grep someprocess'

For commands that might hang:

for i in {1..10}; do timeout 5s ps aux | grep someprocess; done

For maximum portability across different Unix-like systems, stick to POSIX-compliant syntax:

i=0
while [ $i -lt 10 ]; do
    ps aux | grep someprocess
    i=$((i+1))
done

The simplest way to run a command multiple times in Bash is using a for loop. Here's the basic syntax:

for i in {1..10}; do
    ps aux | grep someprocess
done

This will execute your command exactly 10 times. The {1..10} is a brace expansion that generates numbers from 1 to 10.

For more control, you can use a while loop with a counter:

count=0
while [ $count -lt 10 ]; do
    ps aux | grep someprocess
    ((count++))
done

For frequent use across multiple machines, consider adding this to your .bashrc:

function run_multiple() {
    local times=$1
    shift
    for ((i=0; i<times; i++)); do
        "$@"
    done
}

# Usage:
run_multiple 10 ps aux | grep someprocess

When monitoring processes, you might want delays between runs:

for i in {1..5}; do
    ps aux | grep someprocess
    sleep 2  # 2 second delay
done

For quick interactive use, here's a compact version:

for i in {1..5}; do ps aux | grep someprocess; done

If you need parallel execution (GNU Parallel required):

seq 10 | parallel -j4 "ps aux | grep someprocess"

This runs 4 instances in parallel until completing 10 total runs.

For maximum portability across different machines, stick to basic shell constructs. The for loop with brace expansion works in most modern Bash versions, while the arithmetic version (for ((i=0; i<10; i++))) is even more portable.