Scripts have been helping people execute a lot of commands and perform complicated tasks like file operations. The next big step in scripting came in the form of automation, which made scripts even more helpful. Automation in Bash (Bourne Again SHell) command language scripts reduces human efforts and errors, improves efficiency, and maintains consistency. In this article, we will be learning about one important control flow statement: the Bash for loop.
A “for loop” in Bash scripting is a control flow statement that allows code to be executed repeatedly based on a list of items or a sequence of numbers. The syntax involves iterating over each item in a list and executing specified commands. Using for loops in Unix based systems is crucial for automation.
Some benefits of using a for loop in Bash are
- Simplify repetitive tasks
- Reduce human effort
- Save plenty of time by executing tasks quickly
- Cut down human errors via automation of processes.
What is a Bash For Loop?
In simple words, a Bash for loop is a control structure to repeatedly execute specified commands for all the items in a list. In a bash for loop, you have to specify a variable and a list or range to execute the commands on.
Bash for loop template
Why Should You Use Bash for Loops?
Because it increases your efficiency and productivity exponentially. Multiple commands can be executed for each item in a list or sequence which drastically reduces the time and effort involved if the same has to be done manually. A lot of operations like system monitoring, data processing, and file processing can be done via bash for loops which adds one more reason why you should use bash for loops.
Here are some relatable examples to get you started in increasing levels of complexity. If you have noticed the script starting with #!/bin/bash, it is called a shebang. Shebang tells the device that this is a bash script and has to be run using Bash shell.
If you would like to print the file size of each file in a directory
The output will be:
If you would like to iterate over multiple directories and compress each file
The output will be:
Off-by-one Error in Bash for Loop
This is a common mistake while using Bash for loops. The off-by-one error occurs when the loop iterates either one time more or one time less. To understand this better, if you would want to iterate a sequence from 1 to 10, you should use {1..5} and not {1..6}.
Recap and Other Ways to Polish Bash for Loops
Congratulations! You are now ready to continue your path in writing perfect for loops in Bash. Time to automate some mundane daily tasks. If you would like to be a bash for loops master, practice your scripting skills with nested loops.
Some references to help you further
- Cheat sheet for Bash commands (external link to RedHat’s official site)
- Bash Scripting 101 – As simplified as possible
- Bash script arguments tutorial
- Bash While Loop Examples