Looping with for and while in Shell
In the world of shell scripting, looping structures are essential for automating repetitive tasks. In this article, we'll delve into two fundamental looping mechanisms in shell scripting: for and while loops. By the end of this guide, you'll have a solid grasp of how to effectively employ these loops to iterate over lists and repeatedly execute commands. Let's get started!
For Loops
The for loop is one of the most straightforward ways to iterate over a sequence of items in shell scripting. It's fantastic for working with lists and performing operations on each element.
Basic Syntax
The basic syntax of a for loop in shell scripting looks like this:
for variable in list
do
command1
command2
...
done
- variable: This will hold the current item from the list during each iteration.
- list: This can be a sequence of numbers or a list of strings.
- command1, command2...: These are the commands that will be executed for each item in the list.
Example: Iterating Over a List of Strings
Let's say we want to print out a list of fruits. Here’s how we can do this using a for loop:
fruits=("apple" "banana" "cherry")
for fruit in "${fruits[@]}"
do
echo "I like $fruit"
done
Output:
I like apple
I like banana
I like cherry
Example: Using a For Loop with a Number Sequence
You can also use for loops with a sequence of numbers. For instance, to print numbers from 1 to 5:
for i in {1..5}
do
echo "Number: $i"
done
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Nested For Loops
You can also nest for loops to perform more complex iterations. For example, let’s create a multiplication table:
for i in {1..5}
do
for j in {1..5}
do
echo "$i * $j = $((i * j))"
done
done
While Loops
While loops offer a different way to iterate through a block of code as long as a particular condition is true. It’s particularly useful when you don’t know in advance how many times you want to loop.
Basic Syntax
The syntax of a while loop is:
while [ condition ]
do
command1
command2
...
done
- condition: The condition to evaluate, which is checked before each iteration.
- command1, command2...: The commands executed as long as the condition is true.
Example: Basic While Loop
Let's create a simple countdown using a while loop:
count=5
while [ $count -gt 0 ]
do
echo "Countdown: $count"
((count--))
done
echo "Blast off!"
Output:
Countdown: 5
Countdown: 4
Countdown: 3
Countdown: 2
Countdown: 1
Blast off!
Reading User Input in a While Loop
You can also read user input within a while loop. For instance, let’s ask a user for their name until they provide a valid entry:
name=""
while [ -z "$name" ]
do
read -p "Enter your name: " name
done
echo "Hello, $name!"
Combining for and while Loops
Sometimes, you may need to combine for and while loops for more advanced tasks. Here’s an example that counts the number of letters in each fruit:
fruits=("apple" "banana" "cherry")
for fruit in "${fruits[@]}"
do
len=${#fruit}
count=0
while [ $count -lt $len ]
do
count=$((count + 1))
done
echo "$fruit has $len letters."
done
When to Use Which Loop
Choosing between for and while loops often comes down to the specific requirements of your script:
- Use a
forloop when you know the number of iterations in advance, such as iterating over a list of items or a range of numbers. - Employ a
whileloop when the number of iterations is uncertain and depends on a certain condition being met.
Looping Techniques
Loop Control: break and continue
Both for and while loops support control flow commands like break and continue:
- break: Exits the loop entirely.
- continue: Skips the current iteration and continues with the next.
Here's an example demonstrating both:
for i in {1..10}
do
if [ $i -eq 5 ]; then
echo "Skipping 5"
continue
fi
if [ $i -eq 8 ]; then
echo "Breaking at 8"
break
fi
echo "Number: $i"
done
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Skipping 5
Number: 6
Number: 7
Breaking at 8
Conclusion
Understanding how to effectively use for and while loops is a vital skill in shell scripting. With these loops, you can automate tasks, manage data, and tackle complex iterations with elegance and precision. Whether you're iterating over lists or executing commands until a condition is met, each loop has its strengths.
As you create your scripts, remember to choose the loop that best fits your needs, and don’t hesitate to combine them for more intricate logic. Happy scripting!