CentOS Debian Mint openSUSE Red Hat Ubuntu

Bash For Loops with Examples

Bash For Loops with Examples

Loops are critical structures in any programming language, and they play a role in executing repetitive tasks that would otherwise be cumbersome and time-consuming to execute in normal code. In bash scripting, loops serve the same purpose and in this guide, we take a closer look at various types of loops and how they are used.

For Loops

A For loop is used for iterating over a list of objects or items. The list can comprise numbers, strings, characters, or even arrays.

A for loop takes the following structure.

for item in list_of_items

do

 command1

 command2

done

Let us take a few examples:

Looping over a list of strings

In the example below, we are iterating over a list of strings – in this case, planets – which comprises four items. After iteration, we will print each item on the lost using the echo command.

for planet in Mercury Venus Earth Mars Jupiter 

do

 echo $planet

done

Then assign execute permissions and run the for_loop.sh bash script. The output displays all the items contained in the list.

$ ./for_loop.sh

Looping over a range of numbers

With for loops, you can also specify a sequence in a range of numbers by defining the starting point and endpoint using the sequence expression provided.

{START..END}

The example below showcases a for loop that displays numbers from 1 to 10

for n in {0..10}

do

 echo value: $n

done

Running the loop gives you the output shown.

Additionally, you can specify the number of stepwise increments between values using the following sequence expression.

{START..END..STEPWISE_INCREMENT}

For example, the loop below displays numbers from 1 to 10 with a step increase of 2 between the values.

for n in {0..10..2}

do

 echo value: $n

done

When executed, the loop yields the following output.

Looping over an array of elements

Also, you can leverage for loops to iterate over an array of items. For instance, here we have an array called ‘MOVIES’ with different elements which are movie titles.

#!/bin/bash

MOVIES=('Happy Feet' 'Who killed Sara' 'Lupin' 'Money Heist' 'House of cards')

for movie in "${MOVIES[@]}"; 

do

 echo Movie: $movie

done

When the script is executed, the for loop iterates over the entire array and prints out the movie titles as shown.

Summary

As you have observed, for loops are quite simple and handy. They make for cleaner code by eliminating repetitive code which is time-consuming for the user. Repetitive tasks can easily be carried out in a few simple lines.

Similar Posts