0
0
Bash Scriptingscripting~5 mins

C-style for loop in Bash Scripting

Choose your learning style9 modes available
Introduction
A C-style for loop helps you repeat a set of commands a specific number of times, just like counting steps in a recipe.
When you want to run a command exactly 5 times.
When you need to process files numbered from 1 to 10.
When you want to count down from 10 to 1.
When you want to repeat a task with a specific start, end, and step.
When you want to automate repetitive tasks in a script.
Syntax
Bash Scripting
for (( initialization; condition; increment )); do
  commands
 done
Initialization sets the starting point, like setting a counter to 0.
Condition is checked before each loop; if false, the loop stops.
Examples
Counts from 0 to 4 and prints each number.
Bash Scripting
for (( i=0; i<5; i++ )); do
  echo $i
done
Counts down from 10 to 1 and prints each number.
Bash Scripting
for (( i=10; i>0; i-- )); do
  echo $i
done
Counts from 1 to 10 in steps of 2, printing odd numbers.
Bash Scripting
for (( i=1; i<=10; i+=2 )); do
  echo $i
done
Sample Program
This script prints 'Step' followed by numbers 1 to 5, showing a simple count.
Bash Scripting
#!/bin/bash
for (( i=1; i<=5; i++ )); do
  echo "Step $i"
done
OutputSuccess
Important Notes
Make sure to use double parentheses (( )) for C-style loops in bash.
Remember to include spaces around the semicolons inside the loop syntax.
Use 'do' and 'done' to mark the start and end of the loop commands.
Summary
C-style for loops repeat commands with a clear start, stop, and step.
They are useful for counting and repeating tasks in bash scripts.
Syntax uses double parentheses and semicolons to separate parts.