Bash Linux For Loop: Syntax and Examples for Efficient Scripting | Learn Now!
Are you looking to improve your scripting skills in Bash on Linux? One of the most powerful and versatile constructs in Bash is the for loop. With the ability to iterate over lists, arrays, files, and even command outputs, the for loop is an essential tool for efficient scripting. In this article, we will explore the syntax and provide examples of various use cases for the Bash Linux for loop. Whether you are a beginner or an experienced scripter, this article will help you master the art of looping in Bash.
Introduction
In Bash, a for loop allows you to iterate over a list of values and perform a set of actions for each value. The basic syntax of a for loop in Bash is as follows:
for variable in list
do
# code to be executed
done
The variable is a user-defined name that represents each value in the list. The list can be a sequence of values, an array, a file, or the output of a command. The code to be executed inside the loop should be indented.
Basic for loop
The basic for loop in Bash allows you to iterate over a list of values and execute a set of commands for each value. Let’s say you have a list of fruits and you want to print each fruit on a new line:
fruits=("apple" "banana" "orange")
for fruit in "${fruits[@]}"
do
echo $fruit
done
In this example, the fruits array contains three elements: “apple”, “banana”, and “orange”. The for loop iterates over each element in the array and the fruit variable represents each element. The echo command is used to print each fruit on a new line.
The output of this script will be:
apple
banana
orange
For loop with a range of numbers
In addition to iterating over a list, you can also use a for loop to iterate over a range of numbers. This can be useful when you need to perform a set of actions a specific number of times. The syntax for a for loop with a range of numbers is as follows:
for (( variable = start; variable <= end; variable++ ))
do
# code to be executed
done
Let’s say you want to print the numbers from 1 to 5:
for (( i = 1; i <= 5; i++ ))
do
echo $i
done
The output of this script will be:
1
2
3
4
5
For loop with command substitution
Another useful feature of the Bash for loop is the ability to iterate over the output of a command. This is known as command substitution. The syntax for a for loop with command substitution is as follows:
for variable in $(command)
do
# code to be executed
done
Let’s say you want to iterate over the files in a directory and perform a specific action on each file:
for file in $(ls)
do
echo "Processing file: $file"
# code to process the file
done
In this example, the ls command lists all the files in the current directory. The for loop iterates over each file and the file variable represents each file. The echo command is used to print a message indicating the file being processed.
For loop with an array
The Bash for loop can also iterate over an array. This allows you to perform a set of actions for each element in the array. The syntax for a for loop with an array is as follows:
for variable in "${array[@]}"
do
# code to be executed
done
Let’s say you have an array of names and you want to print each name:
names=("John" "Jane" "Michael")
for name in "${names[@]}"
do
echo $name
done
The output of this script will be:
John
Jane
Michael
For loop with a file
The Bash for loop can also iterate over the lines of a file. This is useful when you need to perform a set of actions for each line in a file. The syntax for a for loop with a file is as follows:
for variable in $(cat file.txt)
do
# code to be executed
done
Let’s say you have a file called “numbers.txt” that contains the following numbers:
1
2
3
4
5
You can use a for loop to read each line of the file and perform a specific action:
for number in $(cat numbers.txt)
do
echo "Processing number: $number"
# code to process the number
done
In this example, the cat command is used to read the contents of the “numbers.txt” file. The for loop iterates over each line of the file and the number variable represents each line. The echo command is used to print a message indicating the number being processed.
For loop with a wildcard pattern
The Bash for loop can also iterate over a set of files that match a wildcard pattern. This is useful when you need to perform a set of actions on a specific set of files. The syntax for a for loop with a wildcard pattern is as follows:
for variable in path/*
do
# code to be executed
done
Let’s say you have a directory called “images” that contains multiple image files with the extension “.jpg”. You can use a for loop to perform a specific action on each image file:
for image in images/*.jpg
do
echo "Processing image: $image"
# code to process the image
done
In this example, the images/*.jpg pattern matches all the files in the “images” directory with the extension “.jpg”. The for loop iterates over each matched file and the image variable represents each file. The echo command is used to print a message indicating the image being processed.
For loop with a command output
In addition to iterating over the output of a command using command substitution, you can also use a for loop to iterate over the lines of the command output directly. This can be useful when you want to process the output of a command line by line. The syntax for a for loop with a command output is as follows:
command | while read -r variable
do
# code to be executed
done
Let’s say you want to iterate over the lines of a file and perform a specific action on each line. You can use the cat command to read the file and the while read loop to iterate over each line:
cat file.txt | while read -r line
do
echo "Processing line: $line"
# code to process the line
done
In this example, the cat file.txt command reads the contents of the “file.txt” file. The while read -r loop iterates over each line of the command output and the line variable represents each line. The echo command is used to print a message indicating the line being processed.
For loop with a C-style loop
In addition to the basic for loop syntax, Bash also supports a C-style for loop syntax. This allows you to have more control over the loop initialization, condition, and increment. The syntax for a C-style for loop in Bash is as follows:
for (( variable = start; variable <= end; variable++ ))
do
# code to be executed
done
Let’s say you want to print the numbers from 1 to 5 with a step value of 2:
for (( i = 1; i <= 5; i += 2 ))
do
echo $i
done
The output of this script will be:
1
3
5
For loop with a step value
In addition to the C-style for loop syntax, you can also specify a step value for the iteration. This allows you to control the increment or decrement of the loop variable. The syntax for a for loop with a step value is as follows:
for (( variable = start; variable <= end; variable += step ))
do
# code to be executed
done
Let’s say you want to print the even numbers from 2 to 10:
for (( i = 2; i <= 10; i += 2 ))
do
echo $i
done
The output of this script will be:
2
4
6
8
10
For loop with a conditional statement
The Bash for loop can also be combined with a conditional statement to perform actions based on a specific condition. This allows you to control the flow of the loop based on certain criteria. The syntax for a for loop with a conditional statement is as follows:
for variable in list
do
if [ condition ]
then
# code to be executed
fi
done
Let’s say you have a list of numbers and you want to print only the even numbers:
numbers=(1 2 3 4 5)
for number in "${numbers[@]}"
do
if (( number % 2 == 0 ))
then
echo $number
fi
done
In this example, the numbers array contains five elements. The for loop iterates over each element in the array and the number variable represents each element. The if statement checks if the number is even using the modulo operator. If the condition is true, the number is printed.
For loop with a break statement
The Bash for loop can be terminated prematurely using the break statement. This allows you to exit the loop based on a specific condition. The syntax for a for loop with a break statement is as follows:
for variable in list
do
if [ condition ]
then
break
fi
# code to be executed
done
Let’s say you have a list of numbers and you want to print the numbers until you encounter a negative number:
numbers=(1 2 3 -4 5)
for number in "${numbers[@]}"
do
if (( number < 0 ))
then
break
fi
echo $number
done
In this example, the numbers array contains five elements. The for loop iterates over each element in the array and the number variable represents each element. The if statement checks if the number is negative. If the condition is true, the break statement is executed and the loop is terminated. Otherwise, the number is printed.
For loop with a continue statement
The Bash for loop can also skip the remaining iterations of the loop and continue with the next iteration using the continue statement. This allows you to skip certain iterations based on a specific condition. The syntax for a for loop with a continue statement is as follows:
for variable in list
do
if [ condition ]
then
continue
fi
# code to be executed
done
Let’s say you have a list of numbers and you want to skip the odd numbers:
numbers=(1 2 3 4 5)
for number in "${numbers[@]}"
do
if (( number % 2 != 0 ))
then
continue
fi
echo $number
done
In this example, the numbers array contains five elements. The for loop iterates over each element in the array and the number variable represents each element. The if statement checks if the number is odd using the modulo operator. If the condition is true, the continue statement is executed and the remaining code in the loop is skipped. Otherwise, the number is printed.
Conclusion
The Bash Linux for loop is a powerful tool for efficient scripting. With its ability to iterate over lists, arrays, files, and command outputs, you can perform a wide range of actions with ease. Whether you are a beginner or an experienced scripter, mastering the syntax and examples of the Bash for loop will greatly enhance your scripting skills. So start practicing and unleash the full potential of the Bash for loop in your scripts!
FAQs
Q: Can I nest for loops in Bash?
A: Yes, you can nest for loops in Bash. This allows you to perform complex iterations and actions within your scripts. Just make sure to properly indent the nested loops for better readability.
Q: Can I use a variable as the list in a for loop?
A: Yes, you can use a variable as the list in a for loop. This allows you to dynamically generate the list of values based on your script’s logic. Just make sure to properly format the variable to contain the desired values.
Q: Can I use a for loop to iterate over the output of a command with spaces?
A: Yes, you can use a for loop to iterate over the output of a command that contains spaces. By default, Bash uses whitespace as the delimiter for the for loop. However, if your command output contains spaces, you can use the IFS
(Internal Field Separator) variable to change the delimiter to a newline character. For example: IFS=$'n' for variable in $(command)
.