1. Overview

In Linux, while loops are essential tools for automating repetitive tasks and controlling the flow of programs. These loops enable us to execute a block of code repeatedly, provided that a specified condition is true. Moreover, while loops are versatile in that we can include user input as the specified condition, allowing a defined script to behave dynamically based on user input.

In this tutorial, we’ll take a look at using user input as a while loop condition in the Linux shell.

2. Understanding while Loops

Before we dive into using user input, let’s first discuss the concept and syntax of a while loop:

while [condition]; do
    # Code block
done

Let’s break down the syntax of a while loop:

  • while – this is the keyword that initiates the loop
  • [condition] – represents the expression that determines if the loop should continue executing or not
  • do – marks the start of the code block that executes repeatedly
  • # Code block – this comment shows where the set of commands to be executed are defined
  • done – marks the end of the code block; once the interpreter reaches this keyword, it returns to the while keyword to evaluate whether the condition evaluates to true or false

As long as the while loop condition remains true, the code block within the loop is executed repeatedly. In contrast, the loop terminates if the condition evaluates to false.

3. Including User Input Into a while Loop Condition

In shell scripting, using user input as a condition for a while loop adds dynamic execution as it enables us to control the flow of the script based on their input.

3.1. Prompting for User Input

To demonstrate, let’s utilize the read command to prompt the user:

$ read -p "message prompt" variable_name

Let’s analyze this general syntax:

  • -p – this option allows us to display a custom message prompt while waiting for the user input
  • variable_name – represents the variable that we use to store the user input

This command reads a line of text from the standard input and saves it to the specified variable.

3.2. Including User Input

Now, we need to incorporate the captured user input in our loop condition to create an interactive experience. So, let’s first create the script.sh file and paste the content:

#!/bin/bash

read -p "Number of iterations: " iterations_count

counter=0

while [ $counter -lt $iterations_count ]
do
    echo "Iteration: $counter"
    ((counter++))
done

echo "Loop completed."

Let’s discuss the instructions in the script.sh file:

  • #!/bin/bash – this line is known as the shebang, and its purpose is to instruct the system to execute this script using the Bash shell
  • read -p “Number of iterations: ” iterations_count – the read command prompts the user to enter a number, and the user’s input is stored in the iterations_count variable
  • counter=0 – this variable keeps track of the number of times the loop iterates
  • while [ $counter -lt $iterations_count ] – initiates the while loop whereby the condition checks if the value of the counter variable is less than the value of the iterations_count variable
  • do – declares the start of the while loop body
  • echo “Iteration: $counter” – uses the echo command to print the current iteration number
  • ((counter++)) – increases the value of the counter variable by 1 in each iteration; ((…)) allows for the arithmetic operation in Bash
  • done – specifies the end of the loop body
  • echo “Loop completed.” – prints Loop completed to specify that the loop execution is now complete

Once the Bash script is saved, let’s execute it:

$ bash script.sh
Number of iterations: 4
Iteration: 0
Iteration: 1
Iteration: 2
Iteration: 3
Loop completed.

Here, we see that script.sh prompts the user to enter the number of iterations to run and then executes the while loop for that many iterations.

3.3. Validating the User Input

Once we capture the user input, we need to evaluate it to determine whether it meets the required criteria.

So, let’s modify the script.sh file:

#!/bin/bash

read -p "Number of iterations: " iterations_count

# Validate user input
if ! [[ $iterations_count =~ ^[0-9]+$ && $iterations_count -gt 0 ]]; then
    echo "Invalid user input."
    exit 1
fi

counter=0

...

Let’s break down this modification:

  • if ! [[ $iterations_count =~ ^[0-9]+$ && $iterations_count -gt 0 ]]; then – This line initiates an if statement in Bash. The condition ([[…]]) in evaluation consists of two parts joined by the logical AND operator (&&). First, the $iterations_count =~ ^[0-9]+$ part uses the defined regular expression to ensure that the value of iterations_count matches only contains digits (0-9) and that there’s at least one digit present. Next, the $iterations_count -gt 0 part checks if iterations_count is greater than 0.
  • echo “Invalid user input.” – This command prints the error message in the terminal when the condition in the if statement evaluates to false.
  • exit 1 – This line stops the script with an exit code of 1 to indicate an error.
  • fi – This specifies the end of the if statement.

Above, if the user input iterations_count is not a positive integer, the script prints an error message:

$ bash script.sh
Enter the number of iterations: L
Error: Input must be a positive integer.

If the user input iterations_count is valid, the script continues execution.

4. Conclusion

In this article, we explored how to integrate user input into a while loop condition.

We learned that while loops provide flexibility when combined with user input. This is because this combination helps to create dynamic scripts that adapt to user preferences and requirements. Whether it’s managing loop iterations or terminating the execution of a script, making use of user input improves the usability of a script.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments