0
0
Bash Scriptingscripting~5 mins

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

Choose your learning style9 modes available
Introduction
A for loop with a range lets you repeat commands a set number of times easily.
When you want to run a task 10 times in a row.
When you need to process files numbered from 1 to 10.
When you want to print numbers from 1 to 10.
When automating repetitive steps in a script.
When counting or iterating over a fixed sequence of numbers.
Syntax
Bash Scripting
for i in {1..10}
do
  commands using $i
 done
The numbers inside {1..10} define the start and end of the range.
Each loop step sets variable i to the next number in the range.
Examples
Prints numbers 1 to 5 with the word 'Number' before each.
Bash Scripting
for i in {1..5}
do
  echo "Number $i"
done
Counts down from 10 to 1.
Bash Scripting
for i in {10..1}
do
  echo $i
done
Prints even numbers from 2 to 8 using a step of 2.
Bash Scripting
for i in {2..8..2}
do
  echo $i
done
Sample Program
This script counts from 1 to 10 and prints each number with 'Counting:'.
Bash Scripting
#!/bin/bash
for i in {1..10}
do
  echo "Counting: $i"
done
OutputSuccess
Important Notes
Make sure to use double quotes around variables to avoid word splitting.
The range {1..10} works in Bash version 3 and above.
You can change the step by adding a third number like {1..10..2}.
Summary
Use for loops with {start..end} to repeat commands over a number range.
The loop variable changes each time from start to end.
You can customize the range and step size easily.