Bash For Loop – Syntax and Examples

Bash For Loop

Bash For loop is a statement that lets you iterate specific set of statements over series of words in a string, elements in a sequence, or elements in an array.

Following are the topics, that we shall go through in this bash for loop tutorial.

  • For Loop – that iterates over elements of an Array
  • For Loop – that considers white spaces in String as word separators
  • For Loop – that considers each line in string as a separate word
  • For Loop – that iterates over a Sequence
  • For Loop – that uses a Counter
  • For Loop – with break command

For Loop – that iterates over elements of an array

Syntax

For each element in arr  the statements from do till done are executed, and each element could be accessed as i  within the for loop for respective iteration.

For Loop Example

When the above bash for loop example is run in Terminal
 

For Loop – that considers white spaces in String as word separators

Syntax

str is a string

for each word in str the statements from do till done are executed, and word could be accessed within the for loop for respective iteration.

For Loop Example

When the above bash for loop example is run in Terminal
 

For Loop – that considers each line in String as separate word

Syntax

str is a string

for each line that is a line in str, statements from do till done are executed, and line could be accessed within the for loop for respective iteration.

Note: Observe that the only difference between first type of for loop and this one is the double quotes around string variable.

For Loop Example

When the above bash for loop example is run in Terminal
 

For Loop – that iterates over a Sequence

Syntax

for loop is iterated for each element i  in the sequence from m  to n . The element in the sequence, i  is accessible during the iteration.

For Loop Example

When the above bash for loop example is run in Terminal
 

For Loop – that uses a Counter to iterate over elements of an Array

Syntax

Length of an array could be calculated using  ${#array[@]} and the the statements from do till done are could iterated based on a condition. The syntax of for loop might look similar to that of Java For Loop.

For Loop Example

When the above bash for loop example is run in Terminal
 

For Loop – that breaks prematurely with break command

Syntax

BREAKING_CONDITION decides when to break the for loop prematurely. When the breaking condition evaluates to TRUE, then break statement is executed. break command breaks the loop that is immediate to the break statement.

For Loop Example

When the above bash for loop example is run in Terminal
 

Conclusion :

In this Bash TutorialBash For Loop, we have learnt to iterate specific set of statements over words, lines in a string, elements in a sequence or elements in an array with the help of examples.