w3resource

Bash Looping (for, while): Exercises, Solution and Explanation

1.

Write a Bash script that uses a for loop to print numbers from 0 to 10.

Code:

#!/bin/bash

# Using a for loop to print numbers from 0 to 10
for ((i=0; i<=10; i++))
do
    echo $i
done

Output:

0
1
2
3
4
5
6
7
8
9
10

Explanation:

In the exercise above,

The script initializes a variable i to 0 and iterates over it using a for loop. It prints the value of i in each iteration until it reaches 10.

2.

Write a Bash script that utilizes a while loop to count down from 10 to 1 and then prints "Bash Script!".

Code:

#!/bin/bash

# Initializing the counter
ctr=10

# Using a while loop to count down from 10 to 1
while [ $ctr -gt 0 ]
do
    echo $ctr
    ((ctr--))
done

# Printing "Bash Script!" after the countdown
echo "Bash Script!"

Output:

10
9
8
7
6
5
4
3
2
1
Bash Script!

Explanation:

In the exercise above,

The script initializes a counter variable 'ctr' to 10. Then, it enters a while loop that continues as long as 'ctr' is greater than 0. Inside the loop, it prints the current value of 'ctr' and decrements it by 1 in each iteration.

Finally, after the loop, it prints "Bash Script!".

3.

Write a Bash script that prompts the user to input a number and then uses a for loop to print the multiplication table of that number up to 10.

Code:

#!/bin/bash

# Prompting the user to input a number
echo "Input a number:"
read n

# Checking if the input is a valid number
if ! [[ "$n" =~ ^[0-9]+$ ]]; then
    echo "Invalid input. Please input a valid number."
    exit 1
fi

# Using a for loop to print the multiplication table
echo "Multiplication table for $number:"
for ((i = 1; i <= 10; i++))
do
    echo "$n x $i = $((n * i))"
done

Output:

Input a number:
4
Multiplication table for :
4 x 1 = 4
4 x 2 = 8
4 x 3 = 12
4 x 4 = 16
4 x 5 = 20
4 x 6 = 24
4 x 7 = 28
4 x 8 = 32
4 x 9 = 36
4 x 10 = 40
Input a number:
-2
Invalid input. Please input a valid number.

Explanation:

In the exercise above,

The script first prompts the user to input a number and checks if the input is a valid number. Then, it uses a for loop to iterate from 1 to 10 and prints the multiplication table of the input number for each iteration.

4.

Write a Bash script that uses a while loop to continuously prompt the user for their name until they enter "quit" to exit.

Code:

#!/bin/bash

# Initializing the input variable
name=""

# Continuously prompt the user for their name until they enter "quit"
while [[ "$name" != "quit" ]]; do
    # Prompting the user to enter their name
    echo "Input your name (input 'quit' to exit):"
    read name

    # Check if the user wants to exit
    if [[ "$name" == "quit" ]]; then
        echo "Exiting..."
    else
        echo "Hello, $name!"
    fi
done

Output:

Input your name (input 'quit' to exit):
Osiris Lorelle
Hello, Osiris Lorelle!
Input your name (input 'quit' to exit):
Christoffer Klara
Hello, Christoffer Klara!
Input your name (input 'quit' to exit):
quit
Exiting...

Explanation:

In the exercise above,

  • The "while" loop continues as long as the value of '$name' is not equal to 'quit'.
  • Inside the loop, the user is prompted to enter their name.
  • If the user inputs 'quit', the loop exits. Otherwise, it greets the user with their name.

5.

Write a Bash script that utilizes a for loop to iterate through a list of files in the current directory and print each filename.

Code:

#!/bin/bash

# Iterate through the list of files in the current directory
for file in *; do
    # Check if the file is a regular file (not a directory)
    if [[ -f "$file" ]]; then
        echo "$file"
    fi
done

Output:

abc.sh
document.txt
error.log
file1.txt
file2.txt
input.txt
nums.txt
output.txt
sample.txt
test.sh

Explanation:

In the exercise above,

  • The "for" loop iterates through each file in the current directory using the wildcard *, which matches all files and directories.
  • Within the loop, the script checks if each item is a regular file using the -f test operator.
  • If the item is a regular file, its filename is printed to the terminal using the "echo" command.

6.

Write a Bash script that prompts the user to input a number and then uses a while loop to print the factorial of that number.

Code:

#!/bin/bash

# Prompt the user to input a number
echo "Input a number:"
read n

# Initialize variables
factorial=1
ctr=1

# Check if the input is a non-negative integer
if ! [[ "$n" =~ ^[0-9]+$ ]]; then
    echo "Error: Input a non-negative integer."
    exit 1
fi

# Calculate factorial using a while loop
while [ $ctr -le $n ]; do
    factorial=$((factorial * ctr))
    ctr=$((ctr + 1))
done
# Print the factorial
echo "The factorial of $n is: $factorial"

Output:

Input a number:
5
The factorial of 5 is: 120
Input a number:
0
The factorial of 0 is: 1
Input a number:
-4
Error: Input a non-negative integer.

Explanation:

In the exercise above,

  • First, the user is prompted to input a number using the "read" command.
  • The script checks if the input is a non-negative integer using a regular expression.
  • If the input is not a non-negative integer, an error message is printed, and the script exits with a non-zero status.
  • Otherwise, the script initializes variables 'factorial' and 'ctr' to 1.
  • A while loop is used to calculate the factorial of the input number. The loop iterates from 1 to the input number.
  • Within the loop, the 'factorial' variable is updated by multiplying it with the 'ctr' variable.
  • Finally, the factorial of the input number is printed to the terminal.

7.

Write a Bash script that uses a for loop to iterate over a range of numbers from 1 to 20 and prints only the odd numbers.

Code:

#!/bin/bash

# Iterate over a range of numbers from 1 to 20
for ((i = 1; i <= 20; i++)); do
    # Check if the current number is odd
    if ((i % 2 != 0)); then
        echo "$i"
    fi
done

Output:

1
3
5
7
9
11
13
15
17
19

Explanation:

In the exercise above,

  • The script uses a for loop to iterate over a range of numbers from 1 to 20. The loop variable 'i' represents each number in the range.
  • Within the loop, an if statement checks if the current number ('i') is odd using the condition i % 2 != 0.
  • If the condition evaluates to true (meaning 'i' is odd), the current number 'i' is printed to the terminal using the "echo" command.

8.

Write a Bash script that utilizes a while loop to continuously generate a random number between 1 and 50 until it generates a number divisible by 3.

Code:

#!/bin/bash

# Initialize a variable to store the random number
random_number=0

# Loop until a random number divisible by 3 is generated
while true; do
    # Generate a random number between 1 and 50
    random_number=$((RANDOM % 50 + 1))

    # Check if the random number is divisible by 3
    if (( random_number % 3 == 0 )); then
        echo "Random number divisible by 3 generated: $random_number"
        break  # Exit the loop once a number divisible by 3 is found
    fi
done

Output:

Random number divisible by 3 generated: 33
Random number divisible by 3 generated: 48
Random number divisible by 3 generated: 48
Random number divisible by 3 generated: 3

Explanation:

In the exercise above,

  • The script starts by setting up a while loop that continues indefinitely (while true).
  • Inside the loop, it generates a random number between 1 and 50 using the '$RANDOM' variable and the modulo operator (%).
  • The script then checks if the random number is divisible by 3 using the condition random_number % 3 == 0.
  • If the condition is true, indicating that the generated number is divisible by 3, the script prints the number and exits the loop using the "break" statement. If not, the loop continues generating random numbers until a suitable one is found.

9.

Write a Bash script that prompts the user to input a password and keeps prompting until the correct password is entered using a while loop.

Code:

#!/bin/bash

# Define the correct password
password="Pass23$"

# Prompt the user to input a password
while true; do
    echo "Input the password:"
    read user_password

    # Check if the entered password matches the correct password
    if [[ "$user_password" == "$password" ]]; then
        echo "Access granted"
        break  # Exit the loop if the correct password is entered
    else
        echo "Incorrect password. Please try again."
    fi
done

Output:

Input the password:
abcde
Incorrect password. Please try again.
 
Input the password:
pass23$
Incorrect password. Please try again.
 
Input the password:
Pass23$
Access granted

Explanation:

In the exercise above,

  • The script defines the correct password as a variable named 'password'.
  • It starts a while loop that continues indefinitely (while true).
  • Inside the loop, it prompts the user to enter a password using the "read" command.
  • It then checks if the entered password ('$password') matches the correct password ('$correct_password') using an if statement with a string comparison ([[ ... ]]).
  • If the passwords match, the script prints "Access granted" and exits the loop using the "break" statement.
  • If the passwords do not match, the script prints "Incorrect password. Please try again." and the loop continues, prompting the user to input the password again.

10.

Write a Bash script that uses a for loop to iterate over a list of names and prints a greeting message for each name.

Code:

#!/bin/bash

# Define a list of names
names=("Iolanda" "Valeri" "Sheela" "Jana" "Hartwig")

# Iterate over the list of names using a for loop
for name in "${names[@]}"; do
    echo "Hello, $name! Welcome to the Bash script."
Done

Output:

Hello, Iolanda! Welcome to the Bash script.
Hello, Valeri! Welcome to the Bash script.
Hello, Sheela! Welcome to the Bash script.
Hello, Jana! Welcome to the Bash script.
Hello, Hartwig! Welcome to the Bash script.

Explanation:

In the exercise above,

  • The script defines a list of names using an array named "names".
  • It uses a for loop to iterate over each element (name) in the array.
  • Inside the loop, it prints a greeting message for each name using "echo".
  • The '$name' variable holds the value of each name in each iteration of the loop.

Besh Editor:


More to Come !

Do not submit any solution of the above exercises at here, if you want to contribute go to the appropriate exercise page.



Follow us on Facebook and Twitter for latest update.