Bash: Loops

The Bash language supports three basic types of loops (repitition statements):

  • while loop
  • until loop
  • for loop

Example: While loop in Bash

While loops execute the code within them "while" the test condition is true. In this example, the test condition is the variable x being less than or equal to 5.


	#!/bin/bash
	x=1
	while [ $x -le 5 ]
	do
		echo x = $x
		((x++))
	done
	

Output:

  1
  2
  3
  4
  5

Example: While loop in Bash


	#!/bin/bash
	x=5
	while [ $x -gt 0 ]
	do
		echo x = $x
		((x--))
	done
	

Output:

  5
  4
  3
  2
  1

Example: Until loop in Bash

Until loops execute the code within them "until" the test condition is true.


	#!/bin/bash
	x=1
	until [ $x -gt 5 ]
	do
		echo x = $x
		((x++))
	done
	

Output:

  1
  2
  3
  4
  5

Example: For loop in Bash

For loops can be constructed to work in numerous ways in Bash.

The for loop below executes the code within the loop for each item in the auto_makers list.


	#!/bin/bash
	auto_makers='Ford GM Porsche'
	for name in $auto_makers
	do
		echo $name
	done
	

Output:

  Ford
  GM
  Porsche

Example: For loop in Bash

The for loop below executes the code within the loop while x is between 1 and 3.


	#!/bin/bash
	for x in {1..3}
	do
		echo $x
	done
	

Output:

  1
  2
  3

Example: For loop in Bash


	#!/bin/bash
	for x in {3..1}
	do
		echo $x
	done
	

Output:

  3
  2
  1

Example: For loop in Bash

A third parameter can be added to the for loop test condition to "step" (increment) the loop by that value.


	#!/bin/bash
	for x in {15..1..3}
	do
		echo $x
	done
	

Output:

  15
  12
  9
  6
  3

Example: For loop in Bash

The classic C-style for loop also works.


	#!/bin/bash
	for (( x=0; x<5; x++ ))
	do  
	   echo "$x"
	done
	

Output:

  0
  1
  2
  3
  4
  5

Example: For loop in Bash

The for loop below loops through a list using the classic C-format.


	#!/bin/bash
	employees=("Jane Smith" "Bill Hampton" "Mary Jones")
	len=${#employees[*]}
	 
	for (( i=0; i<${len}; i++ ))
	do
		echo "${employees[$i]}"
	done
	

Output:

  Jane Smith
  Bill Hampton
  Mary Jones

Example: For loop in Bash


	#!/bin/bash
	for x in {a..d}
	do
		echo $x
	done
	

Output:

  a
  b
  c
  d