Bash Loops: The Basics
Bash, the Bourne-Again SHell, provides several types of loops that allow you to repeatedly execute a set of commands. Loops are essential for automating tasks, processing data, and writing more efficient and powerful scripts. In this section, we will explore the basic concepts and usage of Bash loops.
For Loop
The for
loop in Bash is used to iterate over a list of items, such as files, directories, or values in an array. The basic syntax for a for
loop is:
for item in list_of_items; do
## commands to be executed for each item
done
Here's an example that iterates over a list of names and prints each one:
for name in Alice Bob Charlie; do
echo "Hello, $name!"
done
While Loop
The while
loop in Bash executes a set of commands as long as a certain condition is true. The basic syntax for a while
loop is:
while condition; do
## commands to be executed as long as the condition is true
done
Here's an example that counts down from 5 to 1:
count=5
while [ $count -gt 0 ]; do
echo "$count"
count=$((count-1))
done
Until Loop
The until
loop in Bash is similar to the while
loop, but it executes the commands as long as the condition is false. The basic syntax for an until
loop is:
until condition; do
## commands to be executed as long as the condition is false
done
Here's an example that prompts the user for input until they enter "yes":
until [ "$input" = "yes" ]; do
read -p "Enter 'yes' to continue: " input
done
By understanding these basic Bash loop constructs, you can automate a wide range of tasks and write more efficient and powerful scripts. In the next section, we will explore how to control the flow of Bash loops.