Skip to main content

How to Loop N Times

• 1 min read
bash

Quick Answer: Loop N Times in Bash

Use a C-style for loop: for ((i=1; i<=5; i++)); do command; done to repeat exactly N times. Or use seq: for i in $(seq 1 5); do command; done. The C-style loop is faster and preferred for fixed iteration counts.

Quick Comparison: N-Times Loop Methods

MethodSyntaxSpeedBest For
C-style forfor ((i=1; i<=N; i++))FastFixed counts, simple
while countercount=0; while ((count<N))FastDynamic, conditional
seq commandfor i in $(seq 1 N)SlowerReadability, steps
until loopuntil ((i>N)); doFastCountdown, negative logic

Bottom line: Use C-style for ((i=1; i<=N; i++)) for best performance and clarity.


Running Code N Times

Sometimes you need to repeat an action a specific number of times. Whether you’re retrying a command, generating test data, or processing a batch, Bash provides clean ways to loop exactly N times without needing an array.

Method 1: C-Style Loop: Run N Times

The simplest approach:

#!/bin/bash

# Run 5 times
for ((i=1; i<=5; i++)); do
  echo "Iteration $i"
done

Output:

Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5

When to Use C-Style N-Times Loops

  • You know the exact number in advance
  • You need the best performance
  • You want readable, common syntax
  • You’re doing simple counting

Method 2: Using a Counter Variable

More explicit approach:

#!/bin/bash

count=0
while (( count < 3 )); do
  echo "Doing something... attempt $((count + 1))"
  ((count++))
done

When to Use Counter Variable Approach

  • You need dynamic control
  • You’re incrementing by non-standard amounts
  • You want explicit variable management

Practical Examples

Retry Logic

#!/bin/bash

# Retry a command up to 3 times
max_retries=3
attempt=0

while (( attempt < max_retries )); do
  ((attempt++))
  echo "Attempt $attempt of $max_retries"

  # Try the command
  if curl -s https://example.com >/dev/null 2>&1; then
    echo "Success!"
    break
  fi

  # Wait before retrying
  if (( attempt < max_retries )); then
    echo "Failed, waiting 2 seconds..."
    sleep 2
  fi
done

if (( attempt == max_retries )); then
  echo "ERROR: Failed after $max_retries attempts"
  exit 1
fi

When to Use Retry Pattern

  • API calls might fail temporarily
  • Network operations are unreliable
  • You want automatic failure recovery
  • You need exponential backoff

Generate Test Data

#!/bin/bash

# Create 10 test files
for ((i=1; i<=10; i++)); do
  filename="test_$i.txt"
  echo "Test file number $i" > "$filename"
  echo "Created: $filename"
done

When to Use Test Data Generation

  • You’re load testing an application
  • You need sample files for testing
  • You’re populating a database
  • You want to create fixtures

Nested Loops: Run N × M Times

Repeat multiple times with a nested loop:

#!/bin/bash

# Outer loop: 3 times
for ((outer=1; outer<=3; outer++)); do
  echo "Outer loop: $outer"

  # Inner loop: 2 times
  for ((inner=1; inner<=2; inner++)); do
    echo "  Inner loop: $inner"
  done
done

Output:

Outer loop: 1
  Inner loop: 1
  Inner loop: 2
Outer loop: 2
  Inner loop: 1
  Inner loop: 2
Outer loop: 3
  Inner loop: 1
  Inner loop: 2

When to Use Nested N Times

  • You’re processing a matrix
  • You have two independent counts
  • You’re generating combinations
  • You’re building hierarchical structures

Using seq Command

Alternative approach with seq:

#!/bin/bash

# Loop from 1 to 5
for i in $(seq 1 5); do
  echo "Number: $i"
done

# Loop with step (every 2)
for i in $(seq 1 2 10); do
  echo "Number: $i"  # Prints: 1, 3, 5, 7, 9
done

# Countdown
for i in $(seq 5 -1 1); do
  echo "$i..."
done
echo "Blastoff!"

When to Use seq Command

  • You need custom step sizes
  • You want readable code
  • You need countdown functionality
  • You prefer iterating values over counters

Running Commands in Background N Times

Execute parallel operations:

#!/bin/bash

# Start 5 background processes
for ((i=1; i<=5; i++)); do
  (
    # This runs in a subshell
    sleep $((i * 2))
    echo "Task $i completed"
  ) &
done

# Wait for all background jobs
wait
echo "All tasks complete"

When to Use Background Loops

  • You want parallel execution
  • You need to run multiple tasks simultaneously
  • You want to use multiple CPU cores
  • You must wait for all jobs to finish

Stress Test

#!/bin/bash

# Stress test a server
iterations=100
success=0
failure=0

for ((i=1; i<=iterations; i++)); do
  echo -n "Request $i... "

  if curl -s --max-time 2 https://myserver.com >/dev/null; then
    echo "OK"
    ((success++))
  else
    echo "FAIL"
    ((failure++))
  fi
done

echo ""
echo "Results: $success success, $failure failure"

When to Use Stress Testing Pattern

  • You’re load testing a server
  • You need to measure performance
  • You want to find breaking points
  • You’re collecting statistics

Timed Loop: Run for N Seconds

Repeat until a time limit:

#!/bin/bash

# Run for 10 seconds
timeout=10
start=$(date +%s)
count=0

while true; do
  now=$(date +%s)
  elapsed=$((now - start))

  if (( elapsed >= timeout )); then
    break
  fi

  ((count++))
  echo "Iteration $count at ${elapsed}s"
  sleep 1
done

echo "Completed $count iterations in ${elapsed} seconds"

When to Use Timed Loops

  • You need to run for a duration, not a count
  • You’re benchmarking throughput
  • You want time-based throttling
  • You’re testing sustained load

Loop with Increment

Use different step sizes:

#!/bin/bash

# Loop every 10: 0, 10, 20, 30
for ((i=0; i<100; i+=10)); do
  echo "Processing: $i"
done

# Loop every 5 from 5 to 50
for ((i=5; i<=50; i+=5)); do
  echo "Step: $i"
done

When to Use Loop with Increment

  • You’re processing data in chunks
  • You need sampling (every 10th item)
  • You want to skip values
  • You’re processing in batches

Quick Reference

# Loop N times (1 to 5)
for ((i=1; i<=5; i++)); do
  echo $i
done

# Loop with step
for ((i=0; i<10; i+=2)); do
  echo $i
done

# While loop N times
i=0
while (( i < 5 )); do
  echo $i
  ((i++))
done

# Using seq
for i in $(seq 1 5); do
  echo $i
done

# Countdown
for ((i=5; i>0; i--)); do
  echo $i
done

Summary

Looping exactly N times is simple with the C-style for loop. Use for ((i=1; i<=N; i++)) for clarity and efficiency. This pattern is perfect for retries, test data generation, and any operation that needs to repeat a fixed number of times. Choose the method based on whether you need fixed counts (C-style), dynamic control (while), or readable steps (seq).