Using For Loops to Iterate Numbers in Linux

For loops are a useful tool in Linux and other programming languages to repeat a section of code. Let's explore a simple example of using a for loop to iterate from 1 to 100 in a Linux bash script.
This can demonstrate how we can automate repetitive tasks with just a few lines of code.
The Basics of For Loops
The basic format of a bash for loop is:
for variable in list
do
commands
done
This will assign each item in list to variable one by one and execute the commands between do and done.
Some key points:
- The
listcan be a sequence of numbers, an array of strings, the output of a command, etc. - The
variableis a temporary placeholder, usuallyi. - The
commandsare executed once per item inlist.
Iterating Numbers with a For Loop
Let's output the numbers 1 through 100 using a simple for loop in bash:
for i in {1..100}
do
echo $i
done
The {1..100} generates a sequence from 1 to 100. This is assigned to $i each iteration, printed, and loops until $i reaches 100.
When we run this, the output will be:
1
2
3
...
100
So with just 5 lines, we can repeat a task 100 times!
Doing More Inside the Loop
Of course, we aren't limited to just printing the numbers. We can perform other operations inside the loop body.
For example, let's print some text along with the number:
for i in {1..100}
do
echo "Count: $i"
done
Now the output would be:
Count: 1
Count: 2
Count: 3
...
Count: 100
We can run Linux commands inside the loop as well:
for i in {1..100}
do
echo "Number: $i" >> counts.txt
done
This will redirect each iteration's text into the file counts.txt.
The key thing to remember is that all the statements between do and done get executed 100 times.
When Are For Loops Helpful?
For loops enable you to avoid repetitively typing the same code or manually iterating over items.
Some examples of when for loops are useful:
- Processing items in an array, file, or sequence
- Iterating through command line arguments
- Repeating execution of Linux commands
- Automating workflows as part of a script
Anything that needs to repeat identically is a good candidate for a for loop.
Conclusion
For loops are useful for automating repetitive tasks in Linux shell scripts. By iterating over a sequence from 1 to 100, we saw how to eliminate duplicate code and programmatically generate output.
The basics are simple - define the variable name, sequence, and loop body. Then you can focus on what code needs to execute each iteration.
For loops help you work more efficiently by avoiding manual repetition. With just a few lines, you can repeat commands 100 times or iterate over long lists programmatically.
As you write more bash scripts, keep for loops in your toolbox to simplify jobs involving iteration, sequences, or repetitive execution. Mastering for loops unlocks the real power of automation using Linux shell scripts.
