Learn Bash

Loops In BASH – Learn BASH | Part 6

learn bash featured image 1

Welcome to the sixth chapter on BASH scripting series. And today we will dive into a very cool topic called looping constructs in computer programming. Loops are important if we have a task that needs repetition. In the previous chapter where we discussed decisions, we made the computer think logically. Combine that with loops and we have an almost humanoid program that can think, work, and repeat the steps throughout the day.

What are loops?

Loops are control flow statements that allow a program to execute the common repetitive task (or statements) up to a particular number of times.​Here’s a simple analogy, we wake up and work through 9 AM till 5 PM then sleep for the night and repeat the same process all over again. So we humans too are kind of in a loop… Work time, time’s up, and repeat again.

​However, the loop we are about to implement as BASH scripts is controlled so it doesn’t execute endlessly. We will further analyze loops by relating to work time duration 9 AM – 5 PM.

  1. Every loop control statement will usually have a starting point and an ending point. In our work duration situation, 9 AM is the starting point and 5 PM (or 15:00 in 24-hour format) is the ending point.
  2. Then there is a counter that increments or decrements the value from the starting point. And once the counter reaches the ending point, the loop stops. Looking back at the work time duration, our counter would increase in small increments (assume hourly) until it reaches 15:00 and then we go home for the night.

Loops in BASH

There are three loop statements in BASH namely: forwhile, and until. The former two ie., for and while loops are popular in most of the other higher level languages such as C, C++, Java, etc. Read on below to learn more about them

for

for is a control flow statement in which a group of statements is executed continuously as long as the condition is true. Below is the syntax for for loop:

for var in list
do
    statements
done

Here var is the starting point and list is the ending point. var will be either incremented or decremented by the list of statements specified in list.

while

Like for loop, while loop executes a group of statement continuously as long as the condition is true. Below is the syntax for while loop:

while condition is true
do
    statements
    increment/decrement
done

​The only difference between a while loop and for loop is that in for loop, increment/decrement counterpart is done on the same line where we wrote our for statement. Whereas, in while loop, increment/decrement part is done after its body of statements is executed.

However, you should note that increment/decrement part after the while body statements is not always the case and may vary depending on the type of BASH script one is implementing (for instance an infinite while loop).

until

until loop is similar to while loop, also executes a group of statement continuously but with an exception in condition statement part where its boolean value is tested for false and not true. So that means, once the condition becomes true the loop exits otherwise the loop continues as long as the condition is false.

until condition is false
do
    statements
    increment/decrement
done

Bash Scripting Examples

for

#!/bin/bash
i=0
for i in 1 2 3 4 5
do
    echo i is $i
done
bash scripting examples for

 In the above for loop, variable i is the starting point and 1 2 3 4 5 are the list. At each iteration I value is displayed on the screen then is incremented by 1 and the loop continues until it reaches 5 after which the loop successfully exits.

while

#!/bin/bash
counter=0
while [ $counter -lt 3 ]
do
    echo counter is now $counter
      # increment counter by 1
    counter=$(( $counter + 1 ))
done

In the above example script, we are comparing if the counter value is less than 3. Since its starting point is 0 the condition results in true boolean value and the while body is executed. Then the variable counter is incremented by 1 and the loop continues. Soon when the counter value reaches 3, the condition results in false boolean value because 3 cannot be greater than 3, the loop successfully exits.

until

#!/bin/bash
counter=0
until [ $counter -gt 3 ]
do
    echo counter is now $counter
    counter=$(( $counter + 1 ))
done
bash examples until loop

Here the condition is set to compare if the counter value is greater than 3. At the starting point, the counter value is 0 so the condition results in false boolean value and the body of statements are executed. When the counter value reaches 4, the condition results in true boolean value and the loop is successfully exited.

Conclusion

Loops in BASH simplify repetitive codes by allowing the programmer to type less but do more. In case you wanted to print “Hello World!” 20 times on your console screen, you have two ways to achieve that: either type 20 Hello World by hand or use a loop that increments up to 20 printing the greeting message. I’m sure you’d go with the latter one right?​Moreover, apart from the controlled loop we practiced in the above example scripts, you can also create a loop that executes infinitely. That’ll be your homework for this topic. I’ll see you in the next article so stay tuned…

Our sponsor - Deploy your server within 3 minutes


Related articles

1 comment

John Lockard April 4, 2019 at 2:25 am

In the ‘for’ example, if you’re going to do a series, rather than listing every item out, you can use brace expansion (see ‘man bash’).
Rather than:
for i in 1 2 3 4 5 6 7 8 9
you can use:
for i in {1..9}
Rather than:
for i in 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
you can use:
for i in {5..20}
If you’d like to increment by something other than “1”, add an additional “..#” for the increment, as such:
for i in {0..100..5}
This will count from 5 to 100 in multiples of 5 (eg. 0, 5, 10, 15, 20, 25, 30, 35, … 90, 95, 100)

Reply

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More