Bird
Raised Fist0
Bash Scriptingscripting~15 mins

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

Choose your learning style10 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.

Practice

(1/5)
1. What does the following Bash loop do?
for i in {1..5}; do echo $i; done
easy
A. Causes a syntax error
B. Prints numbers 1 to 5, each on a new line
C. Prints numbers 0 to 4, each on a new line
D. Prints the string '{1..5}' once

Solution

  1. Step 1: Understand the loop range syntax

    The loop uses {1..5}, which expands to numbers 1, 2, 3, 4, 5.
  2. Step 2: Check the loop body output

    Each iteration prints the current number, so numbers 1 to 5 print on separate lines.
  3. Final Answer:

    Prints numbers 1 to 5, each on a new line -> Option B
  4. Quick Check:

    Range {1..5} loops from 1 to 5 [OK]
Hint: Curly braces {1..5} generate numbers 1 to 5 [OK]
Common Mistakes:
  • Thinking {1..5} is a string, not a range
  • Confusing range start and end values
  • Expecting zero-based counting
2. Which of the following is the correct syntax to loop from 1 to 10 in Bash using brace expansion?
easy
A. for i in {1..10}; do echo $i; done
B. for i in [1..10]; do echo $i; done
C. for i in (1..10); do echo $i; done
D. for i in <1..10>; do echo $i; done

Solution

  1. Step 1: Identify correct brace expansion syntax

    Bash uses curly braces {start..end} for ranges, so {1..10} is correct.
  2. Step 2: Check other options for syntax errors

    Parentheses, square brackets, and angle brackets are invalid for this purpose in Bash loops.
  3. Final Answer:

    for i in {1..10}; do echo $i; done -> Option A
  4. Quick Check:

    Brace expansion uses curly braces {..} [OK]
Hint: Use curly braces {start..end} for ranges in Bash loops [OK]
Common Mistakes:
  • Using parentheses or brackets instead of braces
  • Missing the 'in' keyword
  • Forgetting to close the loop with 'done'
3. What is the output of this script?
for i in {3..6}; do echo $((i * 2)); done
medium
A. 2 4 6 8
B. 3 4 5 6
C. 6 8 10 12
D. Error: invalid arithmetic

Solution

  1. Step 1: Identify loop values

    The loop variable i takes values 3, 4, 5, 6 from {3..6}.
  2. Step 2: Calculate output for each iteration

    Each iteration prints i * 2: 3*2=6, 4*2=8, 5*2=10, 6*2=12.
  3. Final Answer:

    6 8 10 12 -> Option C
  4. Quick Check:

    Multiply each i by 2 [OK]
Hint: Multiply loop variable inside $(( )) for arithmetic [OK]
Common Mistakes:
  • Confusing loop values with output
  • Using single parentheses instead of $(( ))
  • Expecting space-separated output on one line
4. Find the error in this Bash loop:
for i in {1..5} do
echo $i
done
medium
A. Variable $i is not defined
B. Loop body must be on the same line as for
C. Brace expansion syntax is wrong
D. Missing semicolon or newline after {1..5}

Solution

  1. Step 1: Check for syntax correctness in loop header

    The for loop header must end with a semicolon or newline before 'do'. Here, 'do' follows directly after {1..5} without either, causing a syntax error.
  2. Step 2: Verify other parts

    Variable $i is defined by the loop, brace syntax is correct, and loop body can be on next lines.
  3. Final Answer:

    Missing semicolon or newline after {1..5} -> Option D
  4. Quick Check:

    Loop header must end properly before 'do' [OK]
Hint: Put semicolon or newline before 'do' in for loops [OK]
Common Mistakes:
  • Omitting semicolon or newline before 'do'
  • Misunderstanding brace expansion syntax
  • Thinking loop body must be on same line
5. You want to print only even numbers from 2 to 10 using a Bash for loop with brace expansion. Which script achieves this?
hard
A. for i in {2..10..2}; do echo $i; done
B. for i in {1..10}; do if [ $i % 2 == 0 ]; then echo $i; fi; done
C. for i in {2..10}; do echo $((i*2)); done
D. for i in {2..10..3}; do echo $i; done

Solution

  1. Step 1: Understand brace expansion with step

    Brace expansion supports {start..end..step}, so {2..10..2} generates even numbers 2,4,6,8,10.
  2. Step 2: Check other options

    B uses [ ] test which performs string comparison, not arithmetic modulo, so never prints evens; C multiplies numbers incorrectly to 4,6,8,10,12,14,16,18,20; D steps by 3, not 2.
  3. Final Answer:

    for i in {2..10..2}; do echo $i; done -> Option A
  4. Quick Check:

    Use {start..end..step} for stepped ranges [OK]
Hint: Use {start..end..step} to loop with steps in Bash [OK]
Common Mistakes:
  • Not using step in brace expansion
  • Multiplying loop variable instead of stepping
  • Using wrong step size
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard