How To Write A BASH 'for' Loop

How to use the BASH 'for' loop in shell scripts

Bash script in GNU nano on Linux desktop

BASH (which stands for Bourne Again Shell) is a scripting language utilized by most Linux and UNIX-based operating systems.

You can run BASH commands within a terminal window one after the other or you can add the commands to a text file to produce a shell script.

The great thing about writing shell scripts is that you can run them again and again. For example imagine you need to add a user to a system, set their permissions and manage their starting environment. You can either write down the commands on a piece of paper and run them as you add new users or you can write a single script and just pass parameters into that script.

Scripting languages such as BASH have similar programming constructs as other languages. For instance, you can use import parameters to get input from the keyboard and store them as variables. You can then get the script to perform a certain action based on the value of the input parameters.

A key part of any programming and scripting language is the ability to run the same piece of code again and again.

There are a number of ways to repeat code (also known as loops). In this guide, you will be shown how to write a "for" loop.

A for loop repeats a certain section of the code over and over. They're useful so that a series of commands can keep running until a particular condition is met, after which they'll stop.

In this guide, you will be shown five ways to use the for loop within a BASH script.

Before Getting Started

Before you get started with the for loop examples, you need to open a terminal window and follow these steps:

  1. Enter mkdir scripts (learn more about mkdir here).

  2. Enter cd scripts (this changes the directory to scripts).

  3. Enter nano (where n is the example you're working on).

    mkdir scripts, cd scripts, nano commands in Linux terminal
  4. Enter the script.

    Bash script in GNU nano running in Linux terminal
  5. Press CTRL+O to save and CTRL+X to exit.

  6. Run bash (again, with n being the example you're working with).

How to Loop Through a List

#!/bin/bashfor number in 1 2 3 4 5doecho $numberdoneexit 0

The BASH way of using "for" loops is somewhat different to the way most other programming and scripting languages handle "for" loops. Let's break the script down.

In a BASH "for" loop all, the statements between do and done are performed once for every item in the list.

In the above example, the list is everything that comes after the word in (i.e. 1 2 3 4 5).

Each time the loop iterates, the next value in the list is inserted into the variable specified after the word "for". In the above loop, the variable is called number.

The echo statement is used to displayed information to the screen.

Therefore, this example takes the numbers 1 through 5 and outputs them one by one to the screen:

  • 1
  • 2
  • 3
  • 4
  • 5

How to Loop Between a Start and End Point

The trouble with the above example is that if you want to process a bigger list (say 1 to 500), it would take ages to type all the numbers in the first place.

This brings us to the second example which shows how to specify a start and end point:

#!/bin/bashfor number in {1..10}doecho "$number "doneexit 0

The rules are basically the same. The values after the word "in" make up the list to iterate through and each value in the list is placed in the variable (i.e. number), and each time the loop iterates, the statements between do and done are performed.

The main difference is the way the list is formed. The curly brackets {} basically denotes a range, and the range, in this case, is 1 to 10 (the two dots separate the start and end of a range).

This example, therefore, runs through each number between 1 and 10 and outputs the number to the screen as follows:

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

The same loop could have been written like this, with syntax identical to the first example:

for number in 1 2 3 4 5 6 7 8 9 10

How to Skip Numbers in a Range

The previous example showed how to loop between a start and end point, so now we'll look at how to skip numbers in the range.

Imagine you want to loop between 0 and 100 but only show every tenth number. The following script shows how to do just that:

#!/bin/bashfor number in {0..100..10}doecho "$number "doneexit 0

The rules are basically the same. There is a list, a variable, and a set of statements to be performed between do and done. The list this time looks like this: {0..100..10}.

The first number is 0 and the end number is 100. The third number (10) is the number of items in the list that it will skip.

The above example, therefore, displays the following output:

  • 0
  • 10
  • 20
  • 30
  • 40
  • 50
  • 60
  • 70
  • 80
  • 90
  • 100

A More Traditional Looking For Loop

The BASH way of writing for loops is slightly strange when compared to other programming languages.

You can, however, write a for loop in a similar style to the C programming language, like this:

#!/bin/bashfor ((number=1;number < 100;number++)){if (( $number % 5 == 0 ))thenecho "$number is divisible by 5 "fi}exit 0

The loop starts by setting the variable number to 1 (number = 1). The loop will keep iterating whilst the value of a number is less than 100 (number < 100). The value of number changes by adding 1 to it after each iteration (number++).

Everything between the curly braces is performed through each iteration of the loop.

The bit between the braces checks the value of a number, divides it by 5, and compares the remainder to 0. If the remainder is 0 then the number is divisible by 5 and is then displayed on the screen.

For example:

  • 5 is divisible by 5
  • 10 is divisible by 5
  • 15 is divisible by 5

If you want to change the step size of the iteration you can amend the number++ section to be number=number+2, number=number+5, or number=number+10 etc.

This can be further reduced to number+=2 or number+=5.

A Practical Example

For loops can do more than iterate lists of numbers. You can actually use the output of other commands as the list.

The following example shows how to convert audio files from MP3 to WAV:

for file in ./*.mp3dompg -w ./wavs/"${file}".wav "$file"done

The list in this example is every file with the .MP3 extension in the current folder and the variable is a file.

The mpg command converts the MP3 file into WAV. However, you probably need to install this using your package manager first.