Bash. Loops in Bash

Watch out for endless loops!

Looping is a very powerful feature of bash scripting. Loops have many uses.

In this article, you will explore three different bash loop structures. You will also learn how to use loops to iterate over the elements of an array.

In addition, you will learn how to use the break and continue statements to control loops, and finally, you will learn how to create infinite loops.

For loops in Bash

For loops are one of three different types of loop structures that you can use in bash. There are two different styles of writing a for loop.

  • C-style for hinges
  • Using a for loop on a list / range of elements

C-style for loops in Bash

If you are familiar with the C or C ++ programming language, then you will learn the following for loop syntax:

for ((initialize ; condition ; increment)); do
[COMMANDS]
done

Using the above C-style syntax, the following for loop will print “Hello friend” ten times:

for ((i = 0 ; i < 10 ; i++)); do
	echo "Привет друг"
done

The for loop first initializes the integer variable i to zero, then checks the condition (i <10); if true, then the loop echoes "Hello friend" string and increments i by 1, and then the loop starts over and over until i is greater than 10.

[email protected]:~$ bash hello.sh 
Привет друг
Привет друг
Привет друг
Привет друг
Привет друг
Привет друг
Привет друг
Привет друг
Привет друг
Привет друг

List / Range for Loops in Bash

There is also another variation on the for loop syntax that is especially useful if you are working with a list of files (or strings), a range of numbers, arrays, command output, and so on. The list / range syntax for a loop is:

for item in [LIST]; do
[COMMANDS]
done

For example, the following for loop does the same thing as the C-style for loop you created in the previous section:

for i in {1..10}; do
	echo "Привет друг"
done

The var.sh script below will list all files and directories that exist in the / var directory:

#!/bin/bash

for i in /var/*; do
	echo $i 
done

Below is an example of the output when running the var.sh script:

[email protected]:~$ ./var.sh
/var/backups
/var/cache
/var/crash
/var/lib
/var/local
/var/lock
/var/log
/var/mail
/var/metrics
/var/opt
/var/run
/var/snap
/var/spool
/var/tmp

While loops in bash

The while loop is another popular and intuitive loop that can be used in bash scripts. The general syntax for a while loop is as follows:

while [ condition ]; do
[COMMANDS]
done

For example, the following 3 × 10.sh script uses a while loop that prints out the first ten multiples of three:

#!/bin/bash

num=1
while [ $num -le 10 ]; do
	echo $(($num * 3))
	num=$(($num+1))
done

Here is the output from the above script:

[email protected]:~$ ./3x10.sh
3
6
9
12
15
18
21
24
27
30

First, he initialized the variable num to 1; then the while loop will run as long as num is less than or equal to 10. Inside the enclosure while looping, the echo command prints on NUM multiplied by three and then it increments Num from 1.

Before loops in Bash

If you are working in C / C ++, you may be looking for a do-while loop, but it is not in bash.

There is another kind of loop in bash. The syntax for the while loop is the same as for the while loop:

until [ condition ]; do
[COMMANDS]
Done

The key difference between an until loop and a while loop is the test condition. The while loop will run as long as the test condition is met; on the other hand, loop until the test condition is false!

For example, you can easily create a 3x10sh script with a bye loop instead of a until loop; the trick here is to negate the test condition:

#!/bin/bash

num=1
until [ $num -gt 10 ]; do
	echo $(($num * 3))
	num=$(($num+1))
done

Note that negating a check condition [$ num -le 10]; equally [$ num -gt 10];

More on loops in bash scripting

Now that you are familiar with loops in bash scripting

If you’ve been following this series from the beginning, you should be familiar with arrays in bash.

For loops are often the most popular choice when it comes to iterating over the elements of an array.

For example, the following prime.sh script iterates and prints out each element in an array of primes:

#!/bin/bash

prime=(2 3 5 7 11 13 17 19 23 29)
for i in "${prime[@]}"; do
	echo $i
done

This is the output of the prime.sh script:

[email protected]:~$ ./prime.sh
2
3
5
7
11
13
17
19
23
29

Using Break and Continue in bash loops

Sometimes, you may want to exit the loop prematurely, or skip the loop iteration. You can use the break and continue statements for this.

The break statement ends the execution of the loop and switches program control to the next command or instruction following the loop.

For example, the following loop will only print numbers from one to three:

for ((i=1;i<=10;i++)); do
	echo $i
	if [ $i -eq 3 ]; then
		break
	fi
done

You can also use the continue statement to skip the loop iteration. The loop continues and moves on to the next iteration, but commands after continue statements are skipped in this partial iteration.

For example, the following odd.sh script will only print odd numbers from one to ten, since it skips all even numbers:

#!/bin/bash
for ((i=0;i<=10;i++)); do
	if [ $(($i % 2)) -ne 1 ]; then
		continue
	fi
	echo $i
done

Here is the result that prints out odd numbers:

[email protected]:~$ ./odd.sh
1
3
5
7
9

Endless loops in bash

An endless cycle is a cycle that goes on forever; this happens when the loop check condition is always true.

In most cases, infinite loops are the result of human logical error.

For example, someone who might want to create a loop that prints the numbers 1 through 10 in descending order might mistakenly create the following infinite loop:

for ((i=10;i>0;i++)); do
	echo $i
done

The problem is that the loop keeps incrementing i by 1. To fix this, you need to replace i ++ with i– like this:

for ((i=10;i>0;i--)); do
	echo $i
done

In some cases, you can intentionally create infinite loops to wait for an external condition in the system to be met. You can easily create an infinite for loop like this:

for ((;;)); do
	[COMMANDS]
done

If you want to create an endless while loop instead, you can create it like this:

while [ true ]; do
	[COMMANDS]
done

This brings us to the end of our Bash for beginners article. Hope you enjoyed doing looping in bash!

Stay tuned for next week’s news as you learn how to reuse code in bash scripts by creating functions.

Sidebar