Understanding Linux Bash For Loops

For Loops are a useful tool in Linux bash scripting that allows you to repeat a section of code a set number of times. Getting familiar with bash for loops can help you automate repetitive tasks and write more efficient shell scripts.
In this beginner's guide, we'll cover the basics of how bash for loops work and how you can apply them in your own scripts.
The Basics of Bash For Loops
A bash for loop allows you to specify a piece of code and the number of times you want to repeat that code. Here is the basic syntax of a for loop:
for variable in list
do
commands
done
Let's break this down:
variable- A variable name you define that will increment through the list each iteration of the looplist- A list of items you want to iterate through. This could be a sequence of numbers, a list of strings, an array, the output of a command, etc.commands- The commands you want to execute in the loop, which will run once per item in the list
The for loop proceeds through the list value by value, executing the commands section each time with variable set to the current list item. The done keyword signifies the end of the loop body.
Here is a simple example that prints the numbers 1 through 5:
for i in 1 2 3 4 5
do
echo $i
done
When you run this, it will print each number on its own line.
Iterating on Lists and Commands
In addition to numeric sequences, you can iterate through strings and variable expansions using for loops:
for name in Jim John Sarah
do
echo "Hello $name"
done
This will print a greeting for each name.
You can also iterate through command substitutions by placing a command inside $( ):
for file in $(ls)
do
echo $file
done
This will print the name of each file in the current directory.
Using C-Style For Loops
Bash also offers C-style for loops which are more familiar if you have experience with other programming languages:
for (( i=1; i<=5; i++ ))
do
echo $i
done
Here we set an initial value for i, a condition to evaluate each iteration, and an increment step to execute after each loop. This compact syntax lets you define the for loop in one line without an explicit list.
Controlling the Loop with Conditions
You can wrap an if statement inside a for loop to add logic that controls when to continue or exit:
for (( i=1; i<=10; i++ ))
do
if [ $i -gt 5 ]
then
break
fi
echo $i
done
This will print numbers 1 through 5, then exit the loop using break once we're over 5.
You can also use continue to move immediately to the next iteration without executing the rest of the block.
Also read - Monitoring File Copy Progress in Linux
Applying For Loops to Automate Tasks
Bash for loops is very useful for handling repetitive tasks like iterating through a list of files, strings, or numbers.
Some examples of automation use cases include:
- Renaming groups of files by adding sequence numbers
- Processing logs or data files stored in a directory
- Generating reports by looping through records in a database
- Downloading groups of remote assets or content
Anything that involves repeats is a good candidate for a for loop to simplify your bash scripting.
The key is structuring your data in a way that makes sense to loop through. Arrays provide an effective way to build up collections of data for iteration.
When to Avoid For Loops
While for loops are designed to save effort on repetitive tasks, overusing loops can sometimes make your scripts longer and more difficult to understand. Too many layers of nested loops can become complex.
Here are some cases where avoiding for loops may be advisable:
- The task can be accomplished easily with simple bash commands
- You need to process just a single item
- The iterations are dependent on prior results (using while loops instead)
- Too many loops create convoluted or unreadable code
Learning when not to use looping statements is just as valuable as knowing when to apply them.
Aim for balance and simplicity whenever possible.
Optimizing Performance of For Loops
If you do require loops for heavy data processing, there are some best practices that can help optimize performance:
- Use local variables with
localdeclaration - Avoid unneeded process forks with
waitcommand - Redirect costly output to
/dev/nullwhen possible - Choose faster glob patterns like
*.txtover slower ones like* - Test and benchmark different approaches to find the fastest
Fine-tuning bash loops allow you to increase the efficiency for intensive operations.
Also read - Slice the First Part of Files with Cut on Linux
Conclusion
Bash for loops provides a tool to repeat tasks and iterate over lists programmatically. Using simple for, C-style for (( )), and nested for loops with if logic allows you to script a wide variety of tasks.
Looping brings the benefits of automation and programmability to your shell scripts. But it can also create complexity when overused. Find the right balance for your use case.
Following best practices for performance, readability, and simplification ensures you fully leverage the power of bash for loops. Implementing loops judiciously helps organize your scripts and make your work more productive.
