
Loops are programming constructs that continuously execute specific commands unless interrupted. For instance, the while loop in Bash is a control structure that runs commands if a condition evaluates to true. You can use while loops to handle user input, read files, and execute a series of commands continuously.
This article explains how to use the while loop in Bash for various tasks such as reading files, handling user input, and automating processes.
while Loop Command SyntaxThe while loop in Bash follows this syntax:
In the above command:
while: Starts the while loop.condition: Sets the condition that you want to evaluate.do: Marks the beginning of the loop's body including the commands to execute when the condition evaluates to true.done: Marks the end of the loop and stops execution when the condition evaluates to false.while Loops in BashFollow these steps to create a while loop in Bash using a shell environment or script.
Create a new inline while loop to continuously increment a numeric variable's value up to a certain number, such as 10.
Output:
In the above inline while loop, the $x -le 10 condition evaluates to true if the variable x is less than or equal to 10 and outputs the current item's value while incrementing it using the ((x++)) command. Inline while loops allow you to execute conditions in Bash without creating a script which is important when evaluating files or capturing real-time user input.
Create a new while.sh script that tests if a variable is less than a number, such as 10, prints the current value, and increments the variable until the condition evaluates to false.
Add the following contents to the while.sh file.
Save and close the file.
In this example, the while loop in Bash checks if the variable is less than 10, and outputs the current value.
Run the script using Bash.
Output:
Create a new while-script.sh script.
Add the following contents to the file to create a while loop that uses input redirection < instead of a condition to read the file contents line by line.
Save and close the file.
In the above script, the while loop uses the input redirection command < to input the system user information file /etc/htpasswd to the read command and iterate over all lines in the file. The IFS= option keeps all whitespaces in the file.
Run the script using Bash.
Output:
while LoopsInfinite While loops run indefinitely each time a condition evaluates to true unless terminated or interrupted. The : command creates an infinite loop that continuously executes a series of commands. Infinite loops are useful in logging and monitoring tasks that output continuous data. Follow the steps below to create an infinite while loop that continuously runs unless you stop it using Ctrl + C.
Create a new infinite.sh script.
Add the following contents to the infinite.sh file.
Save and close the file.
In the above script, the while loop uses the : option to create an infinite loop that outputs the This is an Infinite loop message, press <CTRL + C> to stop message. The sleep 1 declaration instructs the loop to run every second.
Run the script using Bash.
Output:
while LoopsNested While loops execute multiple commands at different levels to perform complex iterative tasks. They allow you to use a loop inside another loop to handle complex tasks. Follow the steps below to create nested while loops in Bash.
Create a new nested.sh script.
Add the following contents to the nested.sh file.
Save and close the file.
In the above script, the nested while loop performs data pairing tasks by iterating over each element in the app_name array variable to pair non-identical package names. The outer while loop iterates through all elements in the array, while the inner loop pairs each service with others using the j variable value in the outer loop to compare the position of each element in the array.
Run the script using Bash.
Output:
To control the flow of a while loop, conditional statements like if-else are essential. Visit the if-else in Bash guide for more information.
break Statement in while LoopsThe break statement terminates and exits a loop when a condition evaluates to true. In the following steps, use the break statement to control the flow of a while loop.
Create a new break.sh script.
Add the following contents to the break.sh file.
Save and close the file.
In the above script, the break statement terminates the loop when the var variable reaches 10 and outputs the The loop test is complete! message when the loop stops.
Run the script using Bash.
Output:
continue Statement in while LoopsThe continue statement stops the current iteration in a while loop and starts the next iteration when a specific condition evaluates to true. You can combine the continue and if statements to test for a specific result in a loop to start the next iteration without stopping the loop. Follow the steps below to use the continue statement in a while loop.
Create a new continue.sh script.
Add the following contents to the continue.sh file.
Save and close the file.
In the above script, the while loop uses an if conditional statement to compare if the current value is equal to 5. The continue statement starts the next iteration and ignores other commands in the loop.
Run the script using Bash.
Output:
while Loops with Conditional StatementsConditional statements (if, case, or if-else) control a loop's flow by using the results of a loop's iteration to execute specific commands. You can also combine conditional statements with break and continue commands. In the following steps, use the if statement to control a while loop.
Create a new if-while.sh script.
Add the following contents to the if-while.sh file.
Save and close the file.
The above script uses the if-then conditional statement in a while loop to check if the current var variable value is divisible by 2 to evaluate the result as odd or even.
Run the script using Bash.
Output:
while Loops with FunctionsYou can use while loops with functions to create reusable commands and perform different tasks for each condition. Functions work with conditional statements within a loop to execute reusable code or commands at different intervals. Follow the steps below to use a while loop with multiple functions to perform different actions whenever a condition evaluates to true.
Create a new functions-while.sh script.
Add the following contents to the functions-while.sh file.
Save and close the file.
In the above script, the app_name array stores elements from the user's input, and the while loop iterates over each element in the indexed array that is less than the var variable's value. The loop uses an if-then statement to evaluate if the current list item is help or execute the matching pattern using a case conditional statement. The ((var++)) command increments the current var variable value to iterate over all array elements.
Run the script using Bash.
Enter one or more application names, such as apache or mysql when prompted.
Output:
You have used the while loop in Bash to evaluate specific conditions and continuously execute tasks or commands. The while loops are important when evaluating user inputs, variables, or multiple conditions to achieve a specific result. You can use while loops with other Bash features, such as for loops, conditional statements, arrays, and variables to run continuous tasks.
0 Comments
Be the first to comment and share your perspective with the community.