The for loop in Unix-like operating systems is a fundamental control structure in shell scripting. It allows you to iterate over a list of items or the output of a command, performing a set of commands for each item. This can be highly useful for automating repetitive tasks.
for variable in list
do
commands
done- variable: The name of the variable that will take on each value in the list, one at a time.
- list: A list of items, which can be hardcoded values, the output of a command, or a range.
- commands: The commands to execute for each item in the list.
for color in red green blue
do
echo "Color: $color"
doneOutput:
Color: red
Color: green
Color: bluefor i in {1..5}
do
echo "Number: $i"
doneOutput:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5for file in $(ls *.txt)
do
echo "Processing $file"
doneOutput:
Processing file1.txt
Processing file2.txt
Processing file3.txtSome shells, like bash, support a C-style syntax for for loops:
for ((i=1; i<=5; i++))
do
echo "Number: $i"
doneOutput:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5for file in /path/to/directory/*
do
echo "Found file: $file"
# Add commands to process the file here
donefor file in *.conf
do
cp "$file" "/backup/directory/$file.bak"
echo "Backed up $file to /backup/directory/$file.bak"
donefor file in *.jpg
do
mv "$file" "${file%.jpg}.jpeg"
echo "Renamed $file to ${file%.jpg}.jpeg"
doneservices=("nginx" "mysql" "php-fpm")
for service in "${services[@]}"
do
systemctl status $service
doneYou can nest for loops to handle more complex scenarios:
for dir in /path/to/parent/*
do
echo "Directory: $dir"
for file in "$dir"/*
do
echo " File: $file"
done
doneThe for loop is an essential tool in shell scripting, providing a way to automate repetitive tasks by iterating over lists of items or command outputs. By mastering the for loop, you can significantly enhance your ability to write efficient and effective shell scripts.