Bash for Loop Tutorial with Examples

Loops are one of the most popular mechanisms used in programming and scripting languages. As a popular scripting language Bash provides different loop mechanisms in order to iterate, enumerate, or run repetitive tasks easily. In daily operations, a lot of different tasks may require repetitive actions that can be accomplished by using different loops.

Bash Loop Types

Before starting to learn loop usage we should know that there are 3 type of loop. We can also call this as 3 keywords can be used to create a loop in bash.

  • for loop is the most known and used loop type which is generally looped over a given list, array, etc.
  • while loop is mainly used to loop for a specific condition
  • until the loop is not popularly used

for Loops

Lets start with the for loop which will iterate over the given list or array of items. for loop has the following syntax.

for ITEM in ITEMS
do
   CODE
done
  • ITEMS is an array or list which contains all items to be iterated step by step. The list can be a series of strings separate with spaces, range of numbers, the output of a command, file content and array, etc.
  • ITEM is a single value that is selected from the ITEMS in a sequential manner. Every item in the ITEMS will be set as an ITEM in each step.
  • CODE is the code or body part where operations or tasks will be completed and ITEM can be used for different purposes.

Loop over Number Range

Bash for loop can be used to loop or iterate over the given number range. {START..END} is used to specify the START and END of the numbers or number list. In the following example, we will start from 1 and iterate to the 10 with the for loop.

for i in {1..10}
do
  echo "Number: $i"
done

The output will be like below.

Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Number: 6
Number: 7
Number: 8
Number: 9
Number: 10

In the previous example, we have increased one by one but we can also change the increment value. The syntax of the number range will be {START..END..INCREMENT} where INCREMENT is the increment value. In this example, we will increment 3.

for i in {0..21..3}
do
  echo "Number: $i"
done

The output will be like below. which will start from 0 and end at 21.

Number: 0
Number: 3
Number: 6
Number: 9
Number: 12
Number: 15
Number: 18
Number: 21

Alternatively, we can decrement the number range by using the for loop. We will just put the higher value as start and lower value as the end. In the following example, we will decrement from 10 to 1.

for i in {10..1}
do
  echo "Number: $i"
done

The decrement from 10 to 1 with the for loop will output the following text.

Number: 10
Number: 9
Number: 8
Number: 7
Number: 6
Number: 5
Number: 4
Number: 3
Number: 2
Number: 1

Loop over Number Array

Bash arrays can be also iterated with the for loop easily. The array contains single or multiple items which are formatted as string and delimited with spaces. In the following example we will create an array names sites and put some web site names. then we will iterate over these sites items and print to the console.

sites=('poftut.com' 'wisetut.com' 'linuxtect.com' 'pythontect.com' 'windowstect.com')

for site in "${sites[@]}"; do
   echo "Site name is $site"
done

The output will belike below.

Site name is poftut.com
Site name is wisetut.com
Site name is linuxtect.com
Site name is pythontect.com
Site name is windowstect.com

C-style For Loop

The most popular programming language for Linux administrators is C and Bash also provides a C-style for loop in order to iterate between items. C-style for loop is very similar to the C programming language for loop where initialization, step and test values exist. The C-style for loop has the following syntax.

for ((INITIALIZATION; CONDITION; STEP))
do
   CODE
done
  • INITIALIZATION is generally a variable that will set a value and executed only one the for statement started.
  • CONDITION is a logic statement that will be checked in every step or iteration whether true or false. If the CONDITION is true the for loop continues if CONDITION is false it ends.
  • STEP is executed in every step in order to change the CONDITION like incrementing numbers.
  • CODE is executed in every step or iteration.
READ  How To Install and Use curl In Linux (Ubuntu, Debian, Mint, CentOS)?

Lets make an example with the C-style Bash for loop. We will make things very simple where we will count from 1 to the 10.

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

The output will be like below.

Number is 1
Number is 2
Number is 3
Number is 4
Number is 5
Number is 6
Number is 7
Number is 8
Number is 9
Number is 10

Alternatively we can inplement this C-style for loop by using ; and putting the do in the same line of the for statement.

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

break Statement – Stop The Loop

break statement can be used in order to stop the bash for loop. While iterating items some conditions may occur where the loop should be stopped and this is generally checked with the if statements. Then using the break statement will end or stop the for loop and exit from the loop. break statement does not have any parameters or options.

for ((i = 1; i<= 10; i++))
do
   if [[ "$i" == '4' ]]; then
      break
   fi

   echo "Number is $i"

done

The output will be like below and the output will end at the 4.

Number is 1
Number is 2
Number is 3

continue Statement – Jump To Next Iteration

continue statement is used to skip a step or iteration in a bash for loop. The continue will do not stop for loop completely just skip the current step. Where the break statement will stop for loop completely and do not continue with the next steps or iteration. The continue generally used with the if statement to check specific condition.

for ((i = 1; i<= 10; i++))
do
   if [[ "$i" == '4' ]]; then
      continue
   fi

   echo "Number is $i"

done

Only the number 4 will be skipped and the for loop will continue.

Number is 1
Number is 2
Number is 3
Number is 5
Number is 6
Number is 7
Number is 8
Number is 9
Number is 10

Infinite Loop

Bash for loop generally used with the start and end values. But in some cases, we may need to implement an infinite loop which will not end until it is stopped externally. Infinite for loops do not have any end but can be stopped with an ending a process or by sending a kill signal externally. The infinite for loop in bash can be implemented like below.

for (( ; ; ))
do
   echo "I go to the infinity"
done

The output will be like below and the infinite loop is stopped with the CTRL+C keys.

I go to the infinity
I go to the infinity
I go to the infinity
I go to the infinity
I go to the infinity
I go to the infinity
I go to the infinity
I go to the infinity
I go to the infinity
I go to the infinity
I go to the infinity
I go to the infinity
^C
$

Leave a Comment