This tutorial aims to guide you on how to implement the while loop in shell scripting. The while loop is a control flow statement that allows the execution of a set of commands repeatedly until a certain condition is met.
What you will learn:
while loopwhile loopwhile loopPrerequisites:
A while loop in shell scripting follows this basic syntax:
while [ condition ]
do
command1
command2
commandN
done
The while loop tests the condition before executing the commands. If the condition evaluates to true, commands between do and done are executed. This process continues until the condition evaluates to false.
Best practices and tips:
Example 1: A simple while loop that counts from 1 to 5.
#!/bin/bash
# Initialize counter variable
counter=1
# While loop
while [ $counter -le 5 ]
do
echo "Counter: $counter"
((counter++)) # Increment counter
done
Expected Output:
Counter: 1
Counter: 2
Counter: 3
Counter: 4
Counter: 5
In this tutorial, you've learned about the while loop in shell scripting, its syntax, and how to use it. You also looked at a simple example that demonstrates the while loop.
The while loop is a powerful tool when used correctly. It allows you to automate repetitive tasks, making your scripts more efficient.
Next Steps:
while loops in your scriptsfor and until loops in shell scriptingAdditional Resources:
Exercise 1: Write a script that prints out all even numbers from 1 to 20.
Solution:
#!/bin/bash
# Initialize counter variable
counter=1
# While loop
while [ $counter -le 20 ]
do
# Check if the number is even
if (( $counter % 2 == 0 ))
then
echo $counter
fi
((counter++))
done
Exercise 2: Write a script that accepts an integer n as input and prints the first n Fibonacci numbers.
Solution:
#!/bin/bash
# Read input
read -p "Enter a number: " n
# Initialize variables
a=0
b=1
echo "The Fibonacci sequence is: "
for (( i=0; i<n; i++ ))
do
echo -n "$a "
fn=$((a + b))
a=$b
b=$fn
done
echo
Remember, practice is the key to mastering any programming language. Happy scripting!