Open In App

Bash Scripting – While Loop

Last Updated : 02 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

A while loop is a statement that iterates over a block of code till the condition specified is evaluated to false. We can use this statement or loop in our program when do not know how many times the condition is going to evaluate to true before evaluating to false.  

The Syntax of a while loop in BASH Scripting

while [ condition ];
do
# statements
# commands
done



If the condition is true then the commands inside the while block are executed and are iterated again after checking the condition. Also if the condition is false the statements inside the while block are skipped and the statements after the while block are executed. 

Looping Example using while statement in Linux

First, we create a text file using a text editor in Linux, in this case we are using `vim` Text Editor.

vim while.sh


#!/usr/bin/bash

a=7
while [ $a -gt 4 ];
do
echo $a
((a–))
done
echo “Out of the loop”

Explanation:

  • #!/usr/bin/bash: This line is called a shebang and indicates the path to the interpreter that should be used to execute the script. In this case, it specifies that the Bash shell should be used.
  • a=7: Initializes a variable named a with the value 7.
  • while [ $a -gt 4 ];: Starts a while loop that continues as long as the value of a is greater than 4.
  • do: Marks the beginning of the code block to be executed within the while loop.
  • echo $a: Prints the current value of the variable a to the console.
  • ((a--)): Decrements the value of a by 1. This is a shorthand way of writing a=$((a - 1)).
  • done: Marks the end of the code block for the while loop.
  • echo "Out of the loop": Prints “Out of the loop” to the console after the while loop has completed.

While Loop in Linux

While Loop in Linux

In summary, this script initializes a variable `a` with the value 7, then enters a while loop that continues as long as `a` is greater than 4. Within the loop, it prints the current value of `a` and decrements it by 1 in each iteration. Once `a` becomes 4 or less, the loop exits, and the script prints “Out of the loop” to the console.

Reading a file with a while loop  

We can read a file with a while loop in BASH.  By parsing certain parameters to the while loop condition, we can iterate over the file line by line or by other groups like characters or words.   

First, we create a text file using a text editor in Linux, in this case we are using `vim` Text Editor.

vim while.sh


#!/usr/bin/bash

file=temp.txt
while read -r line;
do
echo $line
done < “$file”

Explanation:

  • #!/usr/bin/bash: This shebang line specifies that the Bash shell should be used to interpret the script.
  • file=temp.txt: Assigns the string “temp.txt” to the variable file, representing the name of the file to be read.
  • while read -r line;: Initiates a while loop that reads each line from the specified file.
  • do: Marks the beginning of the code block to be executed within the while loop.
  • echo $line: Prints the content of the variable line, which represents the current line being read from the file, to the console.
  • done: Marks the end of the code block for the while loop.
  • < "$file": Redirects the input of the while loop to come from the specified file, in this case, “temp.txt”.

In summary, this script reads each line from the file “temp.txt” and prints it to the console until there are no more lines left in the file. The -r option with the read command is used to ensure that backslashes in the input are treated as literal characters.

read file using while statement in Linux

read file using while statement in Linux

We use the command read to actually fetch the lines or characters from the file. The read command is passed with -r argument which ignores the escaping of characters if the \  appears and hence it is parsed as its.  We read a line from a file mentioned after the done statement. The read command reads a line from the mentioned file and the while loops end when the last line from the file is read ( no line is left to read). 

This is how we can read the contents of the file using a while loop in BASH. 

Infinite while loop

To create an infinite loop using a while loop statement. We don’t need to put any condition in the while loop and hence the loop iterates infinitely. The below is the example of an infinite while loop:

First, we create a text file using a text editor in Linux, in this case we are using `vim` Text Editor.

vim while.sh


#!/usr/bin/bash
while :
do
echo “An Infinite loop”
# We can press Ctrl + C to exit the script
done

Explanation:

  • #!/usr/bin/bash: The shebang line specifies that the Bash shell should be used to interpret the script.
  • while : : Initiates an infinite loop. The : (colon) is a shell built-in command that always returns true, effectively creating an infinite loop.
  • do: Marks the beginning of the code block to be executed within the infinite loop.
  • echo "An Infinite loop": Prints the string “An Infinite loop” to the console in each iteration of the loop.
  • # We can press Ctrl + C to exit the script: This is a comment indicating that you can interrupt the script by pressing Ctrl + C in the terminal. Ctrl + C is a common way to interrupt and terminate running scripts in the terminal.
  • done: Marks the end of the code block for the infinite loop.

In summary, this script creates an infinite loop that continuously echoes the message “An Infinite loop” to the console. The loop can be interrupted and the script exited by pressing Ctrl + C in the terminal.

Infinite loop using While Statement in Linux

Infinite loop using While Statement in Linux

Thus the while loop in the script is going to iterate for infinite time. We can manually break the loop or the script by CTRL + C.

While loop to iterate for a fixed number of times

We can use a while loop to iterate over a fixed number of times, we can set the condition to be -le or less than equal to a number, and the loop will iterate till the iterator is less than or equal to the number provided in the condition. Also, we need to increment the iterator manually so to keep the loop iterator ticking, or else the loop will go on forever. 

First, we create a text file using a text editor in Linux, in this case we are using `vim` Text Editor.

vim while.sh


#!/usr/bin/bash

i=1

# the number 4 can be the limit to

# iterate the loop

while [ $i -le 4 ];
do
echo $i
((i++))
done

Explanation:

  • #!/usr/bin/bash: The shebang line specifies that the Bash shell should be used to interpret the script.
  • i=1: Initializes a variable named i with the value 1.
  • while [ $i -le 4 ];: Initiates a while loop that continues as long as the value of i is less than or equal to 4.
  • do: Marks the beginning of the code block to be executed within the while loop.
  • echo $i: Prints the current value of the variable i to the console.
  • ((i++)): Increments the value of i by 1. This is a shorthand way of writing i=$((i + 1)).
  • done: Marks the end of the code block for the while loop.

while loop in Linux

while loop in Linux

In the above example, we can see that the loop iterates a defined number of times. As we have initialized the counter to 1 and the condition is to iterate the loop till the iterator is less than or equal to the number in this case 4. Thus, we can change the number in the condition as per our requirement.

Read the command-line argument with getopts options

We can use get ops options to read the input from the command line and if there are multiple arguments, we can check them and parse them one by one using a while loop. getopts is a tool to get user input from the command line, We can have multiple options to parse from the command line, and using getopts and while loops, we can make a professional-looking user input program.

First, we create a text file using a text editor in Linux, in this case we are using `vim` Text Editor.

vim while.sh


#!/bin/bash

while getopts n:a: OPT
do
case “${OPT}” in
n) name=${OPTARG} ;;
a) age=${OPTARG} ;;
*) echo “Invalid option”
exit 1 ;;
esac
done
printf “My name is $name and I am $age years old\n”

Explanation:

  • #!/bin/bash: The shebang line specifies that the Bash shell should be used to interpret the script.
  • while getopts n:a: OPT: Initiates a loop that uses getopts to parse command-line options. The options specified are n and a, both of which are expected to be followed by an argument.
  • do: Marks the beginning of the code block to be executed within the loop.
  • case "${OPT}" in: Starts a case statement that evaluates the value of the option encountered by getopts.
  • n) name=${OPTARG};;: If the option is -n, assigns the value of the corresponding argument to the variable name.
  • a) age=${OPTARG};;: If the option is -a, assigns the value of the corresponding argument to the variable age.
  • *) echo "Invalid option": If an invalid option is encountered, prints an error message to the console.
  • exit 1;;: Exits the script with a non-zero status code, indicating an error.
  • esac: Ends the case statement.
  • done: Marks the end of the code block for the loop.
  • printf "My name is $name and am $age years old\n": Prints a formatted message to the console using the values of `name` and `age` obtained from the command-line options.

While loop in Linux

While loop in Linux

In this case, we have two options namely, the name and the age, you can have multiple options. We need to specify which option are we gonna use the switch case statements and from the command line using -shorthand option. In this case, we have used -n for name and -a for age. We also have a default or invalid case check to endure we do not parse wrong arguments. We can assign the value of the option using the OPTARG variable which parses the value provided to the option. 

The while loop here is used to iterate till there are no options passed from the command line. We check for the -n and -a option and iterate till the carriage return or enter key is pressed and there are no further options to be parsed. 

 C-style while loop

We can use C-styled while loop in BASH, the variables need to be evaluated with BASH style but the overall syntax feels like C. We can use the operators like <,>,<= and so on in the condition of the while loop and hence it is called like the C-styled while loop. 

First, we create a text file using a text editor in Linux, in this case we are using `vim` Text Editor.

vim c-style-while.sh


#!/bin/bash
i=0
while ((i < 12))
do
echo $i
((i+=2))
done

c-style-while

c-style-while

In this example, we can see that the while loop has a condition with non-bash operators like -le, -ge, etc instead we use the C-styled operators in the condition. The rest of the loop is the basic loop as in BASH, the variable or iterator i is incremented by two as we can see in the last statement of the loop body. Thus the loop iterates over 5 times.

While loop to perform operations on a file

We can perform operations on a file, like reading only a particular part of a file. If we have columns that are formatted in a particular fashion, we can use variables to assign them and print them one row data time. 

Here is the example file name “wh.txt”

vim wh.txt



we create a text file using a text editor in Linux, in this case we are using `vim` Text Editor.

vim file-while.sh



Language type released

Python general 1991

Javascript web 1995

Java mobile 1995

Rust embedded 2010

Go backend 2007

we create a text file using a text editor in Linux, in this case we are using `vim` Text Editor.

vim file-while.sh


#!/bin/bash

while read a b c
do
echo $b – $a
done < wh.txt

While loop in Linux

While loop in Linux

In this example, we have three rows, we read the contents by assigning them to the variables a,b, and c, it can be anything you like but remember to use them in the loop body. We can select a particular column like b and a and can print or perform any operations on them. This won’t be reflected in the file though as they are just the local script variables.

Writing to a file using a while loop

We can write to a file by user input in a while loop. We can use the while loop to iterate till we manually exit out of the loop using CTRL + D by saving changes to the file or by CTRL + C for avoiding writing to the file. We use the read command to input the text from the command line and parse it to the file. 

First, we create a text file using a text editor in Linux, in this case we are using `vim` Text Editor.

vim write-wh.sh


#! /bin/bash

file=wh.txt
echo “Enter the content into the file $file”
while read line
do
echo $line >> $file
done

while loop in Linux

while loop in Linux

So from the example above, we were able to enter text into a file using a while loop and read command. To exit out of the loop and save changes to the file, we use the CTRL+ D keys, and to exit out of the loop without saving anything into the file we can use the CTRL + C keys.  Thus we enter the text from the command line to the text file using the read command and a while loop.

Break and continue Using while Loop

Break and continue are essential in a program that deals with loop statements as they control the flow of the loop statements without any explicit conditions. 

Break statement in While Loop

We use break statements to exit out of the loop without waiting for the condition of the while loop to evaluate to false. This statement can be used within a loop block. This can be used to exit out of an infinite loop with a programmatic condition inside the loop and thus maintain the control of the loop.

For example, we have a script that counts from 1 and forever. But we can programmatically break out of the loop using a break statement inside the body of the loop with a condition. 

First, we create a text file using a text editor in Linux, in this case we are using `vim` Text Editor.

vim while.sh



#!/usr/bin/bash

i=1
while :
do
echo $i
if [ $i -eq 20 ]; then
echo “This is the end of the loop”
break
fi
((i++))
done

Break statement while loop in Linux

Break statement while loop in Linux

From the script and the execution, we can see that we were able to break or exit an infinite loop with a conditional statement and the break statement. Thus the break statement is used to get the control flow of a program/script from inside a while loop to break out of the loop without the loop condition evaluating to false.

Continue statement in While Loop

We can use the continue statement to do the opposite of the break statement. It will jump to the start of the loop block and iterate again. This can be used for skipping over certain commands for certain conditions and hence allows a change in the flow of the loop. 

For example, If we have a variable initialized to 1 and we want to display only the numbers divisible by five or in a certain pattern following a condition, we can use continue statements to do just that. This allows iterating over the loop in the desired manner.

First, we create a text file using a text editor in Linux, in this case we are using `vim` Text Editor.

vim while.sh



#!/usr/bin/bash

i=1
while [ $i -lt 30 ];
do
((i++))
if [[ $(( $i % 5 )) -ne 0 ]];
then
continue
fi
echo $i
done

Continue Statement in While loop in linux

Continue Statement in While loop in linux

As we can see the continue statement, jumps to the beginning of the block and starts the execution of the commands by skipping the next commands inside the block.  The while loop iterates for only the value of variable i being less than 30, thus the if condition checks if the variable i is divisible by 5, and if it’s not we iterate over again using continue and increment the value of the variable i. The variable i only gets echoed if it’s divisible by 5, thus the if condition is evaluated to false and we do not encounter a continue statement and carry with the normal flow of the loop. This is done to avoid logging of every number and only print the numbers which do not follow a pattern or condition in the if statement or other conditional statements. 

Frequeltly Asked Questions

1. What is a `while` loop in Bash scripting?

A while loop is a control flow statement in Bash scripting that allows a certain block of code to be executed repeatedly as long as a specified condition is true. The loop provides a way to automate repetitive tasks and is a fundamental construct in scripting and programming.

2. How does the syntax of a `while` loop look in Bash?

The basic syntax of a while loop in Bash is as follows:

while [ condition ]
do
# Code to be executed while the condition is true
done

The `condition` is a test that occurs before each iteration of the loop. If the condition is true, the code within the loop is executed. If the condition is false, the loop exits, and the script continues with the next command after the `done` statement.

3. What is the role of the `(( ... ))` construct in a Bash while loop?

The `(( ... ))` construct in Bash is used for arithmetic operations. In the context of a `while` loop, it is often employed to evaluate arithmetic conditions.

For example: `((i < 10))` checks whether the variable `i` is less than 10. This allows you to use arithmetic expressions directly in the loop condition, making it especially useful when dealing with numeric comparisons.

4. How to create an infinite loop using `while` in Bash?

An infinite loop in Bash can be created by providing a condition that always evaluates to true.

For example:

while true
do
# Code for the infinite loop
done

Alternatively, you can use a non-zero constant in the condition, like `while [ 1 ]`, to achieve the same result. Infinite loops are useful in situations where continuous execution is required until manually interrupted.

Conclusion

In this article we discussed the BASH scripting while loop which proves to be a versatile tool for executing a block of code repeatedly based on a specified condition. The basic syntax involves defining the condition within square brackets, allowing for flexible iterations. The article explores diverse applications of while loops, including reading from files, creating infinite loops, fixed iterations, parsing command-line arguments, and utilizing break and continue statements. From C-style syntax to interactive file writing, each example demonstrates the loop’s adaptability in addressing a range of scripting needs. This comprehensive overview underscores the while loop’s significance in BASH scripting, providing a robust mechanism for controlled repetition and efficient code execution.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads