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 nameda
with the value 7.while [ $a -gt 4 ];
: Starts a while loop that continues as long as the value ofa
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 variablea
to the console.((a--))
: Decrements the value ofa
by 1. This is a shorthand way of writinga=$((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.
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.
Bash Scripting – While Loop
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.
Table of Content
- The Syntax of a while loop in BASH Scripting
- Looping Example using while statement in Linux
- Reading a file with a while loop
- Infinite while loop
- While loop to iterate for a fixed number of times
- Read the command-line argument with getopts options
- C-style while loop
- While loop to perform operations on a file
- Writing to a file using a while loop
- Break and continue Using while Loop
- Frequeltly Asked Questions