0
0
Bash Scriptingscripting~15 mins

for loop with range ({1..10}) in Bash Scripting - Deep Dive

Choose your learning style9 modes available
Overview - for loop with range ({1..10})
What is it?
A for loop with range {1..10} in bash scripting is a way to repeat commands multiple times, counting from 1 to 10. It uses a special syntax that expands the numbers inside curly braces to create a list of values. The loop runs once for each number in this list, allowing you to automate repetitive tasks easily. This is a simple and common way to run commands multiple times in bash.
Why it matters
Without this looping method, you would have to write the same command many times or manually repeat tasks, which is slow and error-prone. Using a for loop with a range saves time and reduces mistakes by automating repetition. It makes scripts more efficient and easier to maintain, especially when dealing with many similar operations.
Where it fits
Before learning this, you should understand basic bash commands and how to run scripts. After mastering for loops with ranges, you can learn more complex loops, conditional statements, and how to process files or user input in scripts.
Mental Model
Core Idea
A for loop with range {1..10} runs a set of commands once for each number from 1 to 10, automating repetition.
Think of it like...
It's like setting up a row of 10 cups numbered 1 to 10, and then pouring water into each cup one by one in order.
for i in {1..10}
└─> Run commands using i
    ├─> i=1: execute commands
    ├─> i=2: execute commands
    ├─> ...
    └─> i=10: execute commands
Build-Up - 7 Steps
1
FoundationBasic for loop syntax in bash
🤔
Concept: Learn the basic structure of a for loop in bash without ranges.
A for loop repeats commands for each item in a list. Example: for item in apple banana cherry do echo $item done This prints each fruit name one by one.
Result
apple banana cherry
Understanding the basic for loop structure is essential before adding ranges, as it shows how bash repeats commands for each list item.
2
FoundationUsing brace expansion for ranges
🤔
Concept: Learn how brace expansion creates a list of numbers in bash.
Brace expansion {1..5} generates the list: 1 2 3 4 5. You can test it by running: echo {1..5} This prints the numbers separated by spaces.
Result
1 2 3 4 5
Knowing brace expansion lets you create number sequences easily, which is the foundation for looping over ranges.
3
IntermediateCombining for loop with range expansion
🤔Before reading on: do you think the loop runs 5 times or 10 times with {1..10}? Commit to your answer.
Concept: Use brace expansion inside a for loop to repeat commands for a numeric range.
Example: for i in {1..10} do echo "Number: $i" done This runs the loop 10 times, printing numbers 1 to 10.
Result
Number: 1 Number: 2 Number: 3 Number: 4 Number: 5 Number: 6 Number: 7 Number: 8 Number: 9 Number: 10
Combining brace expansion with for loops automates repetitive tasks over a numeric sequence, a common scripting pattern.
4
IntermediateUsing variables inside the loop
🤔Before reading on: do you think variables inside the loop keep their value between iterations? Commit to your answer.
Concept: Learn how to use the loop variable to perform actions that change each time.
Inside the loop, the variable (like i) changes each iteration. Example: for i in {1..5} do echo "Square of $i is $((i * i))" done This calculates and prints squares of numbers 1 to 5.
Result
Square of 1 is 1 Square of 2 is 4 Square of 3 is 9 Square of 4 is 16 Square of 5 is 25
Using the loop variable dynamically allows scripts to perform different actions each time, making loops powerful.
5
IntermediateLooping with step increments
🤔Before reading on: does {1..10..2} include 10 or stop before it? Commit to your answer.
Concept: Learn how to add a step value to the range to skip numbers.
You can specify a step in brace expansion: {start..end..step} Example: for i in {1..10..2} do echo $i done This prints odd numbers from 1 to 9.
Result
1 3 5 7 9
Step increments let you control loop frequency, useful for skipping or sampling values.
6
AdvancedLimitations of brace expansion ranges
🤔Before reading on: do you think {1..1000000} is efficient or slow? Commit to your answer.
Concept: Understand the performance and memory limits of large brace expansions.
Brace expansion generates the full list before the loop starts. For very large ranges, this can slow down or crash scripts. Example: for i in {1..1000000} do echo $i done This may be slow or use lots of memory.
Result
Numbers 1 to 1000000 printed slowly or script may fail
Knowing that brace expansion creates the whole list upfront helps avoid performance issues with huge ranges.
7
ExpertAlternatives to brace expansion for large ranges
🤔Before reading on: do you think using seq is better for large ranges than brace expansion? Commit to your answer.
Concept: Learn how to use external commands like seq to handle large or dynamic ranges efficiently.
Instead of brace expansion, use seq: for i in $(seq 1 1000000) do echo $i done seq generates numbers one by one, saving memory. This is better for very large or variable ranges.
Result
Numbers 1 to 1000000 printed efficiently without memory issues
Using seq or similar commands avoids brace expansion limits, enabling scalable scripts for big tasks.
Under the Hood
Brace expansion in bash works by generating all values inside the braces before the loop runs. It creates a list of strings representing each number in the range. The for loop then iterates over this list one by one, assigning each value to the loop variable. This means the entire list exists in memory at once before the loop starts.
Why designed this way?
Brace expansion was designed for simplicity and speed in common cases with small ranges. Generating the full list upfront allows bash to quickly iterate without extra overhead during the loop. Alternatives like seq were left as external tools to handle more complex or large ranges, keeping bash lightweight.
Brace Expansion Process

{1..5}
  │
  ▼
[1, 2, 3, 4, 5]  <-- full list generated before loop
  │
  ▼
for i in list:
  ├─> i=1: run commands
  ├─> i=2: run commands
  ├─> i=3: run commands
  ├─> i=4: run commands
  └─> i=5: run commands
Myth Busters - 4 Common Misconceptions
Quick: Does {1..10} create numbers as strings or integers? Commit to your answer.
Common Belief:Brace expansion creates integer numbers that behave like math numbers.
Tap to reveal reality
Reality:Brace expansion creates strings representing numbers, not actual integer types.
Why it matters:Treating them as numbers without conversion can cause errors in arithmetic or comparisons.
Quick: Does the loop variable keep its value after the loop ends? Commit to your answer.
Common Belief:The loop variable is local to the loop and disappears after it finishes.
Tap to reveal reality
Reality:In bash, the loop variable remains set to its last value after the loop ends.
Why it matters:This can cause unexpected behavior if the variable is used later without resetting.
Quick: Does {1..10..3} include the number 10? Commit to your answer.
Common Belief:The range always includes the end number regardless of step size.
Tap to reveal reality
Reality:The range stops before exceeding the end number; 10 is included only if it fits the step pattern.
Why it matters:Assuming the end is always included can cause off-by-one errors in loops.
Quick: Is brace expansion efficient for very large ranges like {1..1000000}? Commit to your answer.
Common Belief:Brace expansion handles large ranges efficiently without issues.
Tap to reveal reality
Reality:Brace expansion generates the entire list in memory, which can be slow or crash for large ranges.
Why it matters:Using brace expansion for huge ranges can make scripts slow or unusable.
Expert Zone
1
Brace expansion is purely textual and does not perform arithmetic; this means leading zeros or non-numeric strings can behave unexpectedly.
2
The loop variable is global in the script scope, so reusing its name can overwrite important values unintentionally.
3
Using brace expansion inside quotes disables expansion, which can silently break loops if not noticed.
When NOT to use
Avoid brace expansion for very large or dynamic ranges; instead, use external commands like seq or while loops with arithmetic conditions for better performance and flexibility.
Production Patterns
In production scripts, brace expansion is often used for small fixed ranges like retry counts or fixed iterations. For dynamic or large ranges, seq or C-style for loops are preferred to avoid memory issues and improve readability.
Connections
C-style for loops
Alternative looping syntax with explicit initialization, condition, and increment.
Understanding brace expansion loops helps grasp how simpler loops work before moving to more flexible C-style loops in bash.
Sequence generation in Python
Both generate sequences of numbers for iteration but use different syntax and memory models.
Comparing bash brace expansion with Python's range shows how different languages handle sequences and iteration efficiently.
Assembly language loops
Low-level loops use counters and jumps, similar in concept to counting loops in bash but without high-level syntax.
Recognizing that loops at all levels count and repeat tasks helps understand the universal nature of iteration in computing.
Common Pitfalls
#1Using brace expansion with quotes disables expansion, causing the loop to run once with the literal string.
Wrong approach:for i in "{1..5}" do echo $i done
Correct approach:for i in {1..5} do echo $i done
Root cause:Quoting the braces prevents bash from expanding the range, so the loop treats it as a single string.
#2Assuming the loop variable resets after the loop, leading to unexpected values later.
Wrong approach:for i in {1..3} do echo $i done echo $i # expecting empty or reset
Correct approach:for i in {1..3} do echo $i done i=0 # reset variable explicitly if needed
Root cause:Bash keeps the last value of the loop variable after the loop ends, which can surprise users.
#3Using brace expansion for very large ranges causing slow scripts or crashes.
Wrong approach:for i in {1..1000000} do echo $i done
Correct approach:for i in $(seq 1 1000000) do echo $i done
Root cause:Brace expansion generates the entire list in memory upfront, unlike seq which streams numbers.
Key Takeaways
Brace expansion {1..10} creates a list of numbers as strings before the loop runs, enabling simple numeric iteration.
For loops in bash repeat commands for each item in a list, making repetitive tasks easy to automate.
Using step values in brace expansion controls how the loop counts, allowing skipping numbers.
Brace expansion is efficient for small ranges but can cause performance issues with very large ranges.
Alternatives like seq provide scalable looping for large or dynamic ranges, improving script reliability.