Common Use Cases and Practical Examples
The Bash for
loop is a versatile tool that can be applied to a wide range of tasks and scenarios. Here are some common use cases and practical examples:
File and Directory Operations
One of the most common use cases for the Bash for
loop is to perform operations on files and directories. For example, you can use a for
loop to rename or copy multiple files:
#!/bin/bash
for file in *.txt; do
mv "$file" "${file%.txt}.bak"
done
This script will rename all .txt
files in the current directory by replacing the .txt
extension with .bak
.
System Administration Tasks
Bash for
loops can also be used for system administration tasks, such as checking the status of multiple services or restarting a set of servers. Here's an example that checks the status of several services:
#!/bin/bash
services=("apache2" "mysql" "ssh")
for service in "${services[@]}"; do
systemctl status "$service"
done
This script will check the status of the apache2
, mysql
, and ssh
services on the system.
Data Processing and Analysis
for
loops can be used to process and analyze data, such as iterating over the lines of a file or performing calculations on a set of values. Here's an example that calculates the average of a list of numbers:
#!/bin/bash
numbers=(10 15 20 25 30)
sum=0
for num in "${numbers[@]}"; do
sum=$((sum + num))
done
average=$((sum / ${#numbers[@]}))
echo "The average of the numbers is: $average"
This script will output the average of the numbers in the numbers
array.
Automation and Scripting
Bash for
loops are essential for automating repetitive tasks and creating powerful scripts. By combining for
loops with other Bash features, such as conditional statements and functions, you can build complex and versatile scripts that can handle a wide range of automation needs.
The examples provided in this section demonstrate just a few of the many use cases for the Bash for
loop. As you continue to explore and experiment with this powerful control structure, you'll discover even more ways to leverage it in your Bash scripting endeavors.