Bash C Style For Loop Example and Syntax

Bash C Style For Loop Example and Syntax

In Bash, you can use a C-style for loop to iterate over a range of values.

Here is an example of a C-style for loop in Bash:

# Iterate over the values from 1 to 10
for (( i=1; i<=10; i++ )); do
  # Print the value of i
  echo $i
done
Sou‮:ecr‬www.lautturi.com

This loop will iterate over the values from 1 to 10, and print the value of i on each iteration.

The syntax of a C-style for loop in Bash consists of the following elements:

  • for ((: this marks the beginning of the loop.
  • i=1: this sets the initial value of the loop variable i.
  • ; i<=10: this is the loop condition. The loop will continue as long as i is less than or equal to 10.
  • ; i++: this is the loop increment. It increments the value of i by 1 on each iteration.
  • )); do: this marks the end of the loop.
  • echo $i: this is the loop body. It executes the commands inside the loop on each iteration.
  • done: this marks the end of the loop body.

You can use the loop variable (i in this example) to access the current value of the loop counter within the loop body. You can also use other variables and expressions in the loop condition and loop increment to control the loop behavior.

For example:

# Iterate over the values from 1 to 10, incrementing by 2 on each iteration
for (( i=1; i<=10; i+=2 )); do
  # Print the value of i
  echo $i
done

This loop will iterate over the values from 1 to 10, incrementing by 2 on each iteration, and print the value of i on each iteration.

You can also use the break and continue statements inside a C-style for loop to control the flow of the loop. The break statement will exit the loop, and the continue statement will skip the rest of the loop body and move to the next iteration.

For example:

# Iterate over the values from 1 to 10
for (( i=1; i<=10; i++
Created Time:2017-10-27 14:56:34  Author:lautturi