In this tutorial, we will explore the functionality of 'for' loops, particularly in the context of iterating over lists in shell scripting. This is an essential tool for managing and manipulating data lists.
What you will learn:
Prerequisites:
The 'for' loop in shell scripting works similarly to its counterparts in other programming languages. It allows you to repeatedly execute a block of code for a predetermined number of iterations.
Syntax:
for var in list
do
command1
command2
...
commandN
done
In the above syntax, the loop will iterate over each item in the list. For each iteration, the variable 'var' will be set to the current item, and the commands between 'do' and 'done' will be executed.
Best practices and tips:
Here are some practical examples to help you understand 'for' loops better:
Example 1:
#!/bin/bash
# Declare a list of string
nameList="Alice Bob Charlie"
# Use for loop to iterate over the list
for name in $nameList
do
echo "Hello, $name"
done
In this example, the 'for' loop iterates over each name in the 'nameList' string. For each iteration, it prints a message greeting the current name.
The output will be:
Hello, Alice
Hello, Bob
Hello, Charlie
In this tutorial, we have covered the concept of 'for' loops in shell scripting, specifically how to use them to iterate over lists. We've gone through the syntax, semantics, and best practices, and looked at a practical example.
Next Steps:
Additional Resources:
Exercise 1:
Write a script that prints the square of each number in a list of numbers from 1 to 5.
Solution:
#!/bin/bash
# Declare a list of numbers
numberList="1 2 3 4 5"
# Use for loop to iterate over the list
for num in $numberList
do
echo "$((num*num))"
done
Exercise 2:
Write a script that reverses the order of a list of words.
Solution:
#!/bin/bash
# Declare a list of words
wordList="apple banana cherry"
# Use for loop to reverse the list
for word in $wordList
do
reversedList="$word $reversedList"
done
echo $reversedList
Tips for further practice: