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 types of loops. We can also call these 3 keywords that 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

Let’s 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, a 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 10 with the for loop.

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

The output will be like the 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 the start and the 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 strings and delimited with spaces. In the following example, we will create an array of names of sites and put some website names. then we will iterate over these site’s items and print them 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 be like the 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

for Loop with Bash Command

The for loop can be used with bash commands where the bash command output is used as the list which is iterated. The $(COMMAND) is used to execute the bash command and provide a list into the for loop. The items of the list are iterated and assigned into the bash variable i in every step in the following example.

for i in $(ls)
do
   echo $i
done
a
 aaa
 a.c
 blender-2.80
 blender-2.80.tar.gz
 blender.tar
 cities.txt
 cities.zip
 data2
 db.csv
 Desktop
 ...
 Pictures
 Public
 Templates
 text.txt
 Videos

for Loop with Bash String List

The bash for loop can be used to iterate over the given string list. We just provide the list for the for loop like below. The items of the string list are assigned to the variable named str in every step.

for str in I like wisetut
do
   echo $str
done

Alternatively, we can implement this for loop in a more reliable and readable way by using double quotes like below.

for str in "I" "like" "wisetut"
do
   echo $str
done

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 loops is very similar to the C programming language for loops 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 execute only once 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 the 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.

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

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

The output will be like the 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 implement this C-style for loop by using ; and putting them do in the same line as 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 a 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 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 bash for a loop. The continue will not stop for loop completely just skip the current step. Where the break statement will stop for loop completely and not continue with the next steps or iteration. The continue is generally used with the if statement to check specific conditions.

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 is generally used with the start and end values. But in some cases, we may need to implement an infinite loop that will not end until it is stopped externally. Infinite for loops do not have any end but can be stopped with an ending of 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
$

for Loop with File Extensions

The bash for loop can be used to loop over the files with a specific extension by using the glob operator. We just provide the extension to the for loop and every file with the specified extension is assigned to the variable named file in every step. In the following example, we iterate over the files with *.txt extension.

for file in *.txt
do
   echo $file
done
cities.txt
myshell.txt
numbers.txt
text.txt

We can use this method in order to change file extensions. In the following example, we change the *.jpeg extension into the *.jpg .

for f in *.jpeg; do
    mv -- "$f" "${f%.jpeg}.jpg"
done

Redirect Bash for Loop Output

All output created by bash for loop can be redirected easily by using the > operator. In the following example, we redirect the bash for loop output into the file named log.txt .

for file in *.txt
do
   echo $file
done > log.txt

Leave a Comment