Bash C Style For Loop Example and Syntax

In Bash, you can use the for loop to execute a set of commands a specified number of times. The “C-style” syntax of a for loop in Bash looks like this:

for ((expression1; expression2; expression3))
do
commands
done

Here’s what each expression does:

  • expression1: initializes the loop counter. This is executed only once at the beginning of the loop.
  • expression2: defines the condition for running the loop. As long as this expression evaluates to true, the loop will continue to run.
  • expression3: increment/decrement the loop counter. This is executed at the end of each iteration of the loop.

Here’s an example of using a for loop to print the numbers from 1 to 10:

for ((i=1; i<=10; i++))
do
echo $i
done

In this example, expression1 initializes the loop counter i to 1, expression2 defines the condition that the loop will run as long as i is less than or equal to 10, and expression3 increments i by 1 after each iteration of the loop.

Leave a Comment