Imagine you have a list of things to do, like a shopping list, and you check each item off one by one.
A for loop in Bash scripting is similar. It goes through a list of things and does a specified set of tasks for each item. For practical purposes, a loop is like a helper that repeats tasks for you, making sure each item in your list gets equal attention.
The idea of for loops is really handy in Bash, which is the language we use to tell computers running Linux what to do.
Consider the common scenario where you have a bunch of numbers or a list of file names. You can use a for loop to work through them one by one, doing the same thing for each item.
In this article, we’ll explore how to use for loops in Bash. It’s a fun and easy way to make your computer do repetitive tasks without having to do each step yourself!
Table Of Contents
- The Basics of Bash for Loop
- How To Use Bash for Loop in Scripts?
- The Prerequisites
- Example #1: Handling Each Item Separately
- Example #2: Looping Through a Number Range
- Example #3: Looping Through a Range With Increment
- Example #4: Generate Sequences
- Example #5: Use C-Style Syntax for Bash for loops
- Example #6: The Problem of Endless Loops
- Example #7: Exit a Loop Early
- Example #8: Skip Loop Iterations
- Example #9: Looping Through Array Elements
- Example #10: Access Array Indices
- Example #11: Nesting Loops Within Loops
- Example # 12: Iterating Strings
- Example #13: Processing Files in a Directory
- Example #14: Command Substitution
- Example #15: Command Line Arguments
- Conclusion
- FAQ
The Basics of Bash for Loop
A for loop in Bash allows us to repeat actions. A typical syntax of the loop is as follows:
for item in [list]
do
[commands]
done
In this syntax, the item variable takes each value from the list, and the commands are executed for each item.
How To Use Bash for Loop in Scripts?
Now that you know the fundamentals of the Bash for loop, let’s see how you can use it to carry out practical everyday server management and administration tasks. Let’s start with the prerequisites.
The Prerequisites
Before diving into the intricacies of for loops, ensure you have:
- A Linux distribution that supports the Bash shell.
- A basic grasp of using the command line.
Example #1: Handling Each Item Separately
#!/bin/bash
# For loop with colors
for color in red green blue
do
echo $color
done
This script uses the for loop to print each color name.
Example #2: Looping Through a Number Range
#!/bin/bash
# For loop with a number range
for number in {1..5}
do
echo $number
done
This script loops through the range and prints numbers from 1 to 5.
Example #3: Looping Through a Range With Increment
#!/bin/bash
# For loop with number range with increment
for number in {0..10..2}
do
echo $number
done
This script loops through a range and prints even numbers up to 10. During the process, the loop will skip odd numbers to print only the even numbers.
Example #4: Generate Sequences
#!/bin/bash
# For loop with seq command
for number in $(seq 1 5)
do
echo $number
done
The seq statement uses a starting (1) and ending point (5) to generate a sequence from 1 to 5.
Example #5: Use C-Style Syntax for Bash for loops
#!/bin/bash
# For loop in c-style syntax
for ((i = 0; i < 5; i++))
do
echo $i
done
You can use the C language’s syntax for Bash for loops because many sysadmins are familiar with C/C++.
Also Read: How to Read Files Line by Line in a Bash Script [5 Simple Methods Inside!]
Here’s a quick breakdown of the script:
- #!/bin/bash: This line instructs the terminal to use Bash to run the script.
- for ((i = 0; i < 5; i++)): This is the main syntax of the for part. It’s a loop that starts with i equal to 0. After each round of the loop, it adds 1 to i (i++). The loop keeps going as long as i is less than 5.
- do … done: These stop words show where the loop starts and ends.
- Inside the loop: echo $i is the command that runs in each round of the loop. It prints the current value of i to the screen.
So, when you run this script, it prints:
Each number is shown one after the other, from 0 up to 4. This script is a good example of how to do something repeatedly, like counting numbers or using a loop in Bash.
Example #6: The Problem of Endless Loops
#!/bin/bash
# Creating endless loops
for (( ; ; ))
do
echo "Infinite loop, press CTRL +C to exit"
done
It is easy to create endless for loops that run infinitely until you stop the process or the computer runs out of resources. That is why you should be very careful about creating endless loops because your script will continue execution in the terminal.
The easiest way to exit an infinite loop is CTRL+C.
Here’s how an infinite Bash for loop looks like:
Example #7: Exit a Loop Early
#!/bin/bash
# Break the loop early
for number in {1..10}
do
if [ $number -eq 5 ]
then
break
fi
echo $number
done
The usual behavior of a Bash for loop is to exit when the loop execution hits the exit condition. However, you can exit earlier by using the break statement.
In the above script, the for loop is written to exit when the loop counter hits 10. However, the break statement ensures the loop exits earlier (when the counter hits 5).
Example #8: Skip Loop Iterations
#!/bin/bash
#Skipping loop iterations
for number in {1..5}
do
if [ $number -eq 3 ]
then
continue
fi
echo $number
done
By design, a Bash for loop runs through every iteration. However, there are scenarios when you wish to skip the processing of the task for a particular iteration and then continue the loop execution.
For instance, the Bash for loop starts with the execution and prints the numbers 1 and 2. At the third iteration, the loop execution “skips” printing the number 3 and then continues printing the numbers.
Example #9: Looping Through Array Elements
#!/bin/bash
# Looping through array elements
colors=('red' 'green' 'blue')
for color in "${colors[@]}"
do
echo $color
done
Arrays are very popular data structures that store multiple values in consecutive memory locations. This results in fast data retrieval and simplification of data management in scripts.
The above script contains an array named colors. On every iteration, the for loop accesses the array element and prints the value (the name of colors).
Example #10: Access Array Indices
#!/bin/bash
# Access array indices
colors=('red' 'green' 'blue')
for index in "${!colors[@]}"
do
echo $index
done
In some cases, you wish to access the indices of the array elements. In the example script, the for loop prints out the indices of the array instead of the array elements.
Example #11: Nesting Loops Within Loops
#!/bin/bash
# Combining loops within loops
for outer in 1 2
do
for inner in A B
do
echo "$outer$inner"
done
done
You can include for loops within other for loops. This allows you to execute multiple operations without writing multiple loops. Programmers often use nested loops to work with multi-dimensional arrays.
In the sample script, the first for loop (called the outer loop) prints numbers 1 and 2. The second loop (called the inner loop) prints alphabets A and B.
Example # 12: Iterating Strings
#!/bin/bash
# Iterating over strings
for word in "this is a sentence"
do
echo $word
done
Working with strings is a common activity in Bash scripting. The for loop is a great tool for working with strings. In the sample script, the for loop iterates over the string and prints the characters.
Example #13: Processing Files in a Directory
#!/bin/bash
# Processing files in a directory
for file in *.sh
do
echo $file
done
In this sample script, the for loop goes through the entire directory and prints the name of the files. This script presents a basic idea of using the for loop to access all files in a directory that you can expand for more complex tasks.
Example #14: Command Substitution
#!/bin/bash
# Using command output as list
for user in $(cat users.txt)
do
echo $user
done
Instead of outputting to the standard output, you can use the for loop to run commands. This iterative application of commands allows you to process data, fetch multiple resources, and perform similar sysadmin tasks.
In the sample script, we used the for loop to apply the cat command on each line in the file.
Example #15: Command Line Arguments
#!/bin/bash
# Handling script arguments
for arg in "$@"
do
echo $arg
done
The for loop in this sample script accesses the standard Bash argument array (represented by $@) to get the parameters passed to the script execution command.
While the sample script simply prints the arguments passed to it, you can extend this idea into scripts that carry out complex tasks.
Conclusion
The for loop in Bash scripting offers a versatile way to automate tasks. They save time and reduce human error, allowing us to focus on more complex problems. Remember, practice is key to mastering these concepts.
If you’re looking for a reliable hosting provider to test and run your Bash scripts, RedSwitches Bare Metal Hosting offers robust and scalable solutions that cater to all your hosting needs.
RedSwitches offers the best dedicated server pricing and delivers instant dedicated servers, usually on the same day the order gets approved. Whether you need a dedicated server, a traffic-friendly 10Gbps dedicated server, or a powerful bare metal server, we are your trusted hosting partner.
FAQ
Q. What is the syntax for a for loop in Bash?
In Bash, the syntax for a for loop is:
for item in list_of_items;
do
[commands];
done.
Q. How can I use a for loop to iterate through a list of items in Bash?
You can use a for loop in Bash to iterate through a list of items by specifying the list of items after the “in” keyword in the for loop syntax.
Q. Can you provide some useful examples of using a for loop in Bash?
Sure! Some useful examples of using a for loop in Bash include iterating through files in a directory, processing command-line arguments, and iterating through an array of elements.
Q. What is the syntax for an infinite for loop in Bash?
The syntax for an infinite for loop in Bash is: f
or (( ; ; ));
do
[commands];
done.
Q. How do I use a for loop with a command in Bash?
You can use a for loop with a command in Bash by placing the command inside the backticks or using command substitution within the for loop.
Q. What is the break statement used for in a Bash for loop?
The break statement is used in a Bash for loop to exit the loop prematurely based on a certain condition.
Q. Can I use the for loop with conditional statements in Bash?
Yes, you can use the for loop with conditional statements such as if, elif, and else to perform different actions based on specific conditions.
Q. How does the continue statement work in a Bash for loop?
The continue statement in a Bash for loop is used to skip the remaining commands in the loop and move to the next iteration of the loop.
Q. What are some practical examples of using a while loop in Bash?
Some practical examples of using a while loop in Bash include reading input from a file, processing data until a certain condition is met, and continuously executing a script based on certain criteria.
Q. How can I use the Bash for loop in a command-line environment?
You can use the Bash for loop in a command-line environment to perform repetitive tasks, iterate through a list of items, and automate certain processes using Bash commands.