Bash offers different types of loops, while loop is one of them. It runs a block of codes until the given condition is false. The while loop is necessary for automating repetitive tasks. In this article, I will show you 8 distinct example of a while loop in bash. You’ll understand how versatile the while loop is for carrying out several activities. Continue reading.
1. Execute “while” Loop a Certain Number of Times
The while loop can execute a block of codes a certain number of times. For that, a condition has to be set to define how many times the loop will iterate. Follow the script below to see how the while loop is executed 6 times:
#!/bin/bash
number=1
# Iterate the loop for 6 times
while [ $number -le 6 ]
do
echo "Iterating loop for $number times"
(( number++ ))
done
The script is initiated by a variable number with a value of 1. The while [ $number -le 6 ]
starts the while loop and continues as long as the number is less than or equal to 6. The echo command prints the “Iterating loop for $number times” in each iteration and the $number
indicates the current iteration count.
After completing every iteration, the current iteration number is incremented by 1 for the (( number++ ))
syntax. Finally, the loop ends when the condition is no longer true, that is if the number is greater than 6.
This picture shows that the script printed the string “Iterating loop for 1 times” in the first iteration. Thus, the loop runs 6 times.
2. Run “while” Loop Infinite Number of Times
This example shows how to run a while loop an infinite number of times using while :
syntax. The loop executes indefinitely as the condition remains always true. Here’s the bash script to see how the while loop runs a statement for infinite times:
#!/bin/bash
while :
do
echo "Linuxsimply.com"
done
The infinite loop initiates with the while :
. Then the loop continuously echoes “Linuxsimply.com” in the output terminal until it is explicitly terminated by pressing CTRL+C.
As you can see, the while loop keeps printing the string Linuxsimply.com in the terminal since it is an infinite loop.
3. Read File Line With “while” Loop
To read a file line using a while loop, incorporate the read
command with a while loop. The content of a file can be read line by line with this process. In this example, the filename will be taken as a command-line argument. The $1
indicates the first argument passed to the script. To know in detail, check the script below:
#!/bin/bash
filename=$1
# Read file line by line
while read line;
do
echo $line
done < $filename
The script initiates by assigning the value of the 1st command-line argument to the variable filename. Then while read line
reads the entire content of the given file line by line. Finally, the echo
command prints the file content to the console. The done < $filename
redirects the input of the while loop from the standard input to the file specified by the filename.
Execute the script with ./read-line.sh file.txt
and see the following output:
The picture shows each line of the file.txt file content read by the while loop. You can read any file content by replacing the file.txt with your desired filename.
4. Write File Content Using “while” Loop
Any text or content can be written into a file by utilizing the while loop and the read command. Within the while loop, the read
command reads the file line entered by the user. To finish entering file input, press CTRL+D. The content can be appended to a specific file with the >>
operator in bash.
Now, take a look at the following bash script to learn how to use the while loop
to write file content:
#!/bin/bash
echo -n "Enter the filename to create: "
read filename
echo "Enter the content into the file $filename"
while read line
do
echo $line >> $filename
done
Here, the echo -n "Enter the filename to create: "
will ask the user to enter a filename to create a file. Then the read
command reads the user input. The echo "Enter the content into the file $filename"
prompts the user to write the content into the file. After that, while read line
continues to read the file content line by line until it is stopped by pressing CTRL+D and then appends each line in the specified file with the >>
operator.
After running the script, type cat file.txt
to display the file content in the terminal:
You can see in the image that I started by creating a file named file.txt then I entered file content welcome to linuxsimply and hello world. After that, I pressed ENTER and CTRL+D to stop accepting user input. Lastly, the cat command displayed the file content.
5. Read Command-line Arguments Using “while” Loop
To read the command-line arguments in bash, use the getopts
command within the while loop. This command parses the command-line options and their associated values. The while loop repeatedly calls the getopts command to parse each option individually. This procedure can be employed to read multiple options.
Here’s the bash script to see how the getopts
command works with a while loop to read command-line arguments:
#!/bin/bash
while getopts "n:e:a:" OPT; do
case "${OPT}" in
n) name=${OPTARG} ;;
e) email=${OPTARG} ;;
a) age=${OPTARG} ;;
*) echo "Invalid option"
exit 1 ;;
esac
done
echo -e "My name is '$name'\nMy email ID:'$email'\nI am '$age' years old"
The while loop with a getopts
command starts and continues as long as there are options to parse. These options are separated by the colon "n:e:a:"
where n, e, and a take their corresponding value of the variables (name, email ID, age) entered by the user respectively.
Within the while loop, a case
statement is used to check the current options value, and based on the value, it assigns them to the appropriate variable (name, email, age). If any invalid option encounters, the script echoes “Invalid option” and exits with an exit code 1. After parsing all the options, the script outputs the collected information of the user line by line due to the \n
(make a new line).
Run the script to get the following output:
./command-arg.sh -n "smith" -e "[email protected]" -a "40"
You can see all the information of the user (name, email ID, age) in the output. You can read any information by replacing the value of the name, email, and age variable.
6. Skip a Specific Iteration in “while” Loop
This example shows how to skip a specific iteration in a while loop. For that, the continue
command can be applied within the while loop. This statement continues the while loop without executing the iteration specified by a condition. Here’s how:
#!/bin/bash
number=0
while [ $number -lt 6 ]
do
# Increment the value of number by 1
(( number++ ))
if [[ $number == 2 ]]
then
continue
fi
echo "Iteration number: $number"
done
The script initiates with the variable number=0. The $number -lt 6
condition within the while loop states that the loop continues as long as the iteration number is less than 6. Then loop increments the variable number by 1 in each iteration.
The condition $number == 2
within the if statement checks whether the current number is 2. If true, it executes the continue
command which means it skips the rest of the code for this particular iteration and proceeds to the next iteration. Finally, the script prints the “Iteration number: $number” in the terminal.
Due to the continue command, it skips the Iteration number: 2 and continues the loop by printing the rest of the iterations.
7. Calculate Factorial Using “while” Loop
To calculate factorial using a while loop, the multiplication operator *
is used inside the loop. The operator keeps multiplying the current value of the factorial and an input number to get the final result. Copy the script for calculating factorial:
#!/bin/bash
number=$1
factorial=1
while [ $number -gt 0 ]
do
factorial=$(( factorial * number ))
number=$(( number - 1 ))
done
echo "$factorial"
The script initiates with a number=$1 which means the variable number will take the value of the 1st argument as input. The factorial variable starts with a value of 1 and it will store the factorial calculation. while [ $number -gt 0 ]
starts the while loop and continues as long as the number is greater than 0.
Inside the loop, factorial=$(( factorial * number ))
multiplies the current value of the factorial and number and updates the factorial variable. number=$(( number - 1 ))
decrements the number value by 1. Lastly, the echo "$factorial"
prints the final value of the factorial.
Running the script with ./factorial.sh 5
shows the output as:
The image illustrates that 120 is the factorial of 5. You can compute any factorial of your choices with this script.
8. C-Style “while” Loop Example in Bash
This example shows how to use a C-style while loop in bash. As its name suggests, the C-style while loop basically follows the structure of the C programming language. The double parentheses (())
contain the condition in this style loop just like in the C programming language. However, it serves the same function as a basic bash while loop, there is only a syntactic difference.
Follow the script to learn more about the C-style while loop:
#!/bin/bash
i=0
while ((i <= 25))
do
echo $i
((i+=5))
done
First, the variable i is taken with a value of 0. The while ((i <= 25))
loop runs till the value of i is less than or equal to 25. The current value of i is echoed by the echo $i
. ((i+=5))
indicates that the current number will increase by 5 after completing every iteration.
As you can observe, the loop initiated by the value 0 and increased the number by 5 in each iteration and printed the number as long as it equals 25.
Practice Tasks on Bash “while” Loop Example
Do some practices to be an expert in bash while loop. Here are some tasks of bash while loop is given:
- Write a bash while loop script that starts to count from 1 and print a message 10 times.
- Create a bash script of a while loop that prints “Hello world” indefinitely.
- Suppose, you are Asim, your email ID: [email protected], and your age is 25 years old. Now, create a script that reads your information as command-line arguments and gives you the collected information in the terminal.
- Write a C-style while loop that prints all the even numbers from 0 to 10.
Conclusion
In conclusion, I have covered the 8 distinct examples of while loop in bash. A detailed explanation of each example is demonstrated above. I hope you now have a better understanding of the various applications of the bash while loop. Enjoy your day!
People Also Ask
What is a while loop in Bash?
A while loop in Bash is a loop that executes a block of statements repeatedly as long as the specified condition is true. When the condition is false, the loop comes to an end. It helps to automate repetitive tasks.
What is the syntax of the while loop in Bash?
The syntax of the while loop is:
while [ condition ];
do
#Statements to be executed as long as the condition is true
done
It will execute the statements over and over again till the specified condition remains true.
How to create an infinite while loop?
To create an infinite while loop, you can use a while true
statement or while :
structure. The infinite while loop runs forever as the condition always evaluates to true. The syntax of an infinite while loop is:
while true; do
#statements to be executed indefinitely
done
OR,
while : do
#statements to be executed indefinitely
done
How to break a while loop at a certain condition?
To break a while loop at a certain condition, you can use a break
statement inside the condition. Here’s an example bash script for this:
#!/bin/bash
number=1
while :
do
if [ $number -gt 5 ]; then
break
fi
echo “$number”
((number++))
sleep 1s
done
echo “Break the loop”
After running the script, when the number becomes greater than 5, the loop breaks.
What is $1 in shell script?
In a shell script, $1
is a positional parameter that represents the passing of 1st argument to the shell script.
How to write a while loop with two conditions?
To write a while loop with two conditions, you can use the AND or OR operator to connect the conditions.
Here’s the syntax of the while loop with two conditions using the AND
operator:
#!/bin/bash
while [ condition1 ] && [ condition2 ]; do
# Statement to be executed while both conditions are true
done
This script executes the statement if both conditions are true.
Here’s the syntax of the while loop with two conditions using the OR
operator:
#!/bin/bash
while [ condition1 ] || [ condition2 ]; do
# Statement to be executed while at least one condition is true
done
This script executes the statement if at least one condition is true.
Related Articles
- “while true” Loop in Bash [4 Cases]
- How to Increment Number Using Bash “while” Loop [8 Methods]
- One Line Infinite “while” Loop in Bash [4 Examples]
- How to Use Bash Continue with “while” Loop [7 Examples]
- Exit “while” Loop Using “break” Statement in Bash [11 Examples]
- How to Use Bash One Line “while” Loop [8 Examples]
- How to Use “sleep” Command in Bash “while” Loop [6 Examples]
<< Go Back to “while” Loop in Bash | Loops in Bash | Bash Scripting Tutorial
FUNDAMENTALS A Complete Guide for Beginners