A Beginner’s Guide on using for
Loop in Bash
4 min readAug 23, 2024
Introduction
A for
loop in Bash is used to repeat a set of commands a specific number of times. It iterates over a list of items (like strings, numbers, files) and executes the commands for each item in the list.
Basic Syntax of for
Loop
The basic syntax of a for
loop in Bash is:
for variable in list
do
# commands
done
- variable: A placeholder for each item in the list.
- list: A list of values or items.
- commands: The commands that you want to execute for each item in the list.
Iterating Over a List of Values
Let’s start with a simple example where we iterate over a list of names:
#!/bin/bash
for name in Alice Bob Charlie
do
echo "Hello, $name!"
done
Explanation:
- The
for
loop iterates over the listAlice Bob Charlie
. - For each name, the loop executes the
echo
command, greeting each person.
Output
Hello, Alice!
Hello, Bob!
Hello, Charlie!