Bash For Loop

Does your code require repetitive tasks in your Linux or UNIX operating system? A “for loop” statement allows particular commands done continuously until a condition is met, or it becomes “false.”

This programming language statement is an iteration of the loop within the bash script, thus its name, “bash for loop.”

This is particularly useful at simplifying your codes. Rather than making numerous separate codes of command, might as well write a “for loop” in bash syntax just once. It gets the job done fast!

This tutorial containing bash for loop examples will surely help you work your way around improving your programming language skills. Let’s get started!

How does a For Loop using Bash work?

The for loop basically takes each item on the list in a particular order and assigns it to the value of the variable.

It then executes the commands stated in between the do and done keywords. It goes back to the top, gets the next item on the list, and repeats the process until it is over.

Getting Started

Being able to use a loop using bash programming language is relatively easy. Before anything else, here are a few prerequisites:

  • Bash running on Linux, UNIX, or MacOS operating systems
  • Access to the command line

Basic Syntax for Loop Bash

To help us understand how we can use bash for loop statements in specific scenarios, later on, it’s important we familiarize ourselves with the super basic loop syntax. Your loop should look like this:

for ITEM in LIST
do
   COMMANDS
done

where,

LIST – refers to the list of strings, array elements, or outputs of the command.

ITEM – refers to a single item on the list; the variable.

COMMANDS – refers to the set of commands to be executed on the loop.

Bash for Loop Examples

For numeric ranges, you can use these bash loop formats:

for VARIABLE in 1 2 3 4 .. N
do
    command1
    command2
    command3
    commandN
done

Alternatively, you can use these formats as well:

for VARIABLE in sample file1 sample file2 sample file3
do
        command1 on $VARIABLE
        command2
        commandN
done

OR

for OUTPUT in $(Linux-Or-Unix-Command-Here)
do
        command1 on $OUTPUT
        command2 on $OUTPUT
        commandN
done

For example, here is a bash for loop 1-5 variable on a command to output a “Hello” message:

#!/bin/bash
for i in 1 2 3 4 5
do
 echo "Hello $i"
done

where,

#!/bin/bash – to initiate that it is a bash script.

i – refers to the variable. it’s up to you what keyword you wish to assign a variable to.

$i – refers to the individual values of the variables.

1 2 3 4 5 – refers to an example of variables you want to perform the command on.

do – a statement to signal the start of the loops. It executes the instruction N number of times. In this case, 5 times.

echo “Hello $1” – refers to the statement which will be repeated into the number of times it is required. It must be placed in quotation marks to be considered as one variable before proceeding to the next iteration.

done – statement that stops the loops.

This loop example would output this:

Hello 1
Hello 2
Hello 3
Hello 4
Hello 5

If you have a different bash version, you can shorten the given variables this way:

For bash version 3.0+, you can use ” . . “in the loop. It will result in the same example stated above:

#!/bin/bash
for i in {1. .5}
do
  echo "Hello $i"
done

In most cases, you assign a starting and ending value. But for bash version 4.0+, you can use the format {start . . end . . increment} to increase or decrease the value of the variable by each time. An example would be:

#!/bin/bash
for i in {0. .8. .2}
do
  echo "Hello $i"
done

The result will look like this:

Hello 0
Hello 2
Hello 4
Hello 6
Hello 8

Bash for Loop as an Infinity Loop

This iteration of the loop once execution is activated, will not stop unless you press the keys to trigger its end.

The infinity loop format will look like this:

#!/bin/bash
for (( ; ; ))
do
   echo "infinite loops [ hit CTRL+C to stop]"
done

For this loop example, the message “Hello World!” will keep appearing until you press CTRL+C:

#!/bin/bash
for (( ; ; ))
do
  echo "Hello World!"
done

Loops Syntax for Three- Expression Bash

This loop is also called the C-style loop because of its similarities in structure with the C programming language.

It contains three-loop control expressions namely, the initializer (EXP1), the loop test or condition (EXP2), and a counting expression (EXP3).

The format of the bash code will look like this:

for (( EXP1; EXP2; EXP3 ))
do
        command1
        command2
        command3
done

A three-expression bash loop example would be:

#!/bin/bash
for (( c=1; c<=5; c++ ))
do 
   echo "Welcome $c"
done

The output will look like this:

Welcome 1
Welcome 2
Welcome 3
Welcome 4
Welcome 5

The code states that the initial value is 1, as valued in EXP1.

The loop continues to be executed until the condition in EXP2 is met. In this case, the numbers should not be greater than 5. The EXP3 with the ++ sign signifies that the next number comes after an increment of 1.

The Skip and Continue Bash For Loop

Most of the time, our loops will run smoothly and orderly. But in any case you feel the need to step in and alter them, you can.

The continue statement informs the bash file to stop running the current iteration of the loop and head on to the next iteration.

This is often used when you might be going through a series of files and stumble upon one that you have no permission to read.

In this case, the continue statement skips the loop for that variable value and continues to the next. The syntax formatting would look like this:

for i in 1 2 3 4 5
do
 if [condition]
 then
    continue   #Go to next iteration of i in the loop and skip statements3
 fi
 statement
done

Here is an example of a skip and continue bash for loop:

for i in {1..5}
do
  if [[ "$i" == '2' ]]
  then
    continue
  fi
  echo "Welcome $i2"
done
  echo 'Hello!'

The output would be:

Welcome 1
Welcome 3
Welcome 4
Welcome 5
Hello!

The loop did not perform the code when it matched with the continue statement not to show the value of 2.

It moved on to 3, until the last value was met. It then proceeds to the next code which shows the message ‘Hello!’.

Another example to apply the continue statement when looking into a file would be:

#!/bin/bash
FILES="$@"
for f in $FILES
do
        if [ -f ${f}.bak ]
        then
               echo "Skipping $f file..."
               continue 
        fi
        /bin/cp $f $f.bak
done

This sample script backs up all file names specified on the command line. If the .bak file is met, it will skip the command and proceed to the next.

Bash for Loop for Conditional Exit with Break Statement

The break statement directs the bash to exit and leave the loop right away.

Usually, there is a natural iteration statement that will cause the loop to end. But in exceptional cases, you can use the break statement to end it abruptly.

A common scenario is when you are copying files. If the free disk space arrives to a low level, the copying should be put to a halt. The loop stops the operation when the stated condition is met. This is how it would look like:

for i in 1 2 3 4 5
  do
  if [condition]
  then
    break
  fi
  statement
done

To further illustrate this function with array elements:

for country in England Germany Italy France Spain
do
  if [[ "$country" == 'France' ]]; then
    break
  fi
  echo "country: $country"
done
 
echo 'Yes, that’s all!'

And lastly the output:

country: England
country: Germany
country: Italy
Yes, that’s all!

The break statement stops the operation of the loop when the condition becomes true.

In this case, when it arrives at the value ‘France’, It then executes the next code which is the message, Yes, that’s all!

Another example would be when going through file names. The statements will be executed for all values of i until a disaster condition is met, which then breaks the loop.

The next statement is executed and proceeds if everything is good and no disaster condition was met.

#!/bin/bash
for file in /etc/*
do
        if [ "${file}" == "/etc/resolv.conf" ]
        then
               countNameservers=$(grep -c nameserver /etc/resolv.conf)
               echo "Total  ${countNameservers} nameservers defined in ${file}"
               break
        fi
done

Following this shell script, it will go through all stored file names in /etc directory. The for loop will exit and break when /etc/resolv.conf file will be found.

Summary

There’s a lot of things you can do with the bash for loop.

It makes coding easy by allowing you to automate repetitive tasks. You can look through files, or even come up with unique commands, depending on whatever program you are working on. The possibilities are endless!

We hope this basic tutorial has helped you wrap your head around the functions of bash for loop. Just keep practicing and you’ll be excellent in no time!