Exploring Bash — Part 4

Dineshkumaar R
6 min readApr 9, 2024

--

Introduction

Hey Friends, Welcome back to my Bash exploration blog series! Today, we’re delving into the world of Bash loops. Loops are essential for executing repetitive tasks efficiently in Bash scripting. We’ll cover for loops, while loops, until loops, and loop control statements. By the end of this exploration, you’ll have a solid understanding of how to leverage loops to streamline your scripting endeavors. Let’s dive in!

For Loops

For loops in Bash are used for iterating over a predefined list of items or generating sequences of numbers. They are particularly useful for executing a set of commands multiple times.

Syntax of for loops

for item in list
do
# commands to execute
done

Example 1:

#!/bin/bash

for lang in bash Python JavaScript C++
do
echo "I am learning $lang"
done

Each iteration of the loop prints a message indicating the programming language that is being learned, using the value of the ‘lang’ variable.

Example 2:

#!/bin/bash

for (( num = 1; num <= 10; num++ ))
do
square=$((num * num))
echo "The square of $num is $square"
done

Each iteration calculates the square of the current number (num) and prints it out.

While Loops

While loops in Bash allow you to execute a block of code repeatedly as long as a specified condition is true. They are useful for tasks where the number of iterations is not known beforehand.

Syntax of while loops

while condition
do
# commands to execute
done

Example 1:

#!/bin/bash

count=1

while [ $count -le 5 ]
do
echo "Count: $count"
sleep 1 # Pause for 1 second
((count++))
done

echo "Loop finished"

• The script initializes a variable count with a value of 1.
• The while loop continues as long as the value of count is less than or equal to 5.
• Inside the loop:
-It prints the current value of count.
-Pauses execution for 1 second using the sleep command.
-Increments the value of count by 1 in each iteration.
• After the loop finishes executing, it prints “Loop finished”.

Example 2:

#!/bin/bash

# Prompt the user for input
echo -n "Enter something (enter 'exit' to quit):"

# Read user input
read input

# Start a while loop
while [ "$input" != "exit" ]
do
echo "You entered: $input"

# Prompt the user for input again
echo -n "Enter something (enter 'exit' to quit):"
read input
done

echo "Exiting the program"

• The script starts by prompting the user to enter something using echo -n (which doesn’t add a newline at the end) and then reads the input using read.
• It enters a while loop, which continues as long as the input from the user is not equal to “exit”.
• Inside the loop, it echoes back whatever the user entered.
• It then prompts the user for input again, repeating the process until the user types “exit”.
• When the user types “exit”, the loop exits, and the script prints “Exiting the program” before terminating.

Until Loops

Until loops are similar to while loops but execute a block of code until a specified condition becomes true. They are useful for tasks where you want to continue executing code until a certain condition is met.

Syntax of Until Loops

until condition
do
# commands to execute
done

Example 1:

#!/bin/bash

# Generate a random number between 1 and 10
target=$(( (RANDOM % 10) + 1 ))

# Initialize a variable to store the user's guess
guess=0

# Start an until loop
until [ $guess -eq $target ]
do
# Prompt the user to guess the number
echo -n "Guess the number (between 1 and 10): "
read guess

# Check if the guess is correct
if [ $guess -lt $target ]
then
echo "Too low! Try again."
elif [ $guess -gt $target ]
then
echo "Too high! Try again."
fi
done

# Print a congratulatory message when the guess is correct
echo "Congratulations! You guessed the correct number: $target"

• The script generates a random number between 1 and 10 using the $RANDOM variable.
• It starts an until loop that continues until the user’s guess matches the randomly generated number.
• Inside the loop:
- It prompts the user to guess the number.
- It checks whether the guess is too low or too high and provides appropriate feedback.
• When the user’s guess matches the random number, the loop terminates, and the script prints a congratulatory message.

Example 2:

#!/bin/bash

# Set the initial countdown value
countdown=10

# Start an until loop
until [ $countdown -lt 1 ]
do
echo "Countdown: $countdown"
((countdown--))
sleep 1 # Pause for 1 second
done

echo "Time's up!"

This script demonstrates the use of an until loop to implement a countdown timer. It counts down from 10 to 1, pausing for 1 second between each count, and then prints “Time’s up!” when the countdown completes.

Loop Control

Loop control statements ‘break’ and ‘continue’ are used to modify the flow of loops. ‘break’ is used to exit the loop prematurely, while ‘continue’ skips the current iteration and moves to the next one.

Example 1:

#!/bin/bash

for num in 1 2 3 4 5 6 7
do
if [ $num -eq 3 ]
then
continue
fi
echo "Number: $num"
if [ $num -eq 5 ]
then
break
fi
done

• The for loop iterates over the numbers 1 to 7.
• Inside the loop, there’s a conditional check:
- If the current number is 3, continue statement is executed, skipping the rest of the loop body for that iteration and moving to the next iteration.
- If the current number is 5, break statement is executed, which exits the loop immediately.
• The loop prints “Number: <num>” for each iteration, except when the number is 3 (due to continue) and after the number 5 (due to break).

Summary of the blog

1. For loops iterate over a list or generate sequences. Example: Printing messages for each programming language being learned and calculating squares of numbers.
2. While loops execute code while a condition is true. Example: Counting from 1 to 5 with a 1-second pause and prompting user input until “exit” is typed.
3. Until loops execute code until a condition becomes true. Example: Guessing a random number and implementing a countdown timer.
4. Loop control statements, such as break and continue, modify loop flow. Example: Skipping iterations or exiting loops based on conditions.

URL’s :

  1. Exploring bash — Part1 : https://medium.com/@dineshkumaar478/exploring-bash-part-1-3dabf4b5ef9e
  2. Exploring bash — Part2 : https://medium.com/@dineshkumaar478/exploring-bash-part-2-71f341fb5700
  3. Exploring bash — Part3 : https://medium.com/@dineshkumaar478/exploring-bash-part-3-db1fc958eb17

Thank you for taking the time to read my blog. Wishing you a joyful learning experience ahead!

--

--

Dineshkumaar R

🔐 Cyber Security Engineer | Penetration Tester | VAPT Specialist | 🚩 Hackthebox (Pro Hacker) | 🏆 Tryhackme (Guru)