PuTTYgen

Download PuTTYgen - Putty key generator

Bash for Loop (With Examples)

Loops are one of the most powerful and fundamental programming concepts that allow users to execute a command or set of commands repeatedly. The Loops come in very handy for all programmers where they have to run a series of commands repeatedly until it accomplishes certain conditions.

In other words, Loops are easy and best to perform repetitive tasks. Its use is even more significant when working with scripting languages such as Bash. Our article will provide all the basics of the for loops in Bash.

There are various loops constructs such as the while loop, the until loop, the select loop, and the for loop. However, in this article, we will focus on the widely popular ‘the for loop.’ It will cover how and when to use the ‘for pool’ tool.

Aforementioned, Loops are set of commands that a computer executes over and over again until a predefined condition is met. Programmers also have the liberty to break the loop even before the condition is met. Commonly, the Bash For Loop is leveraged for various tasks such as to count files or also look for information. For instance, if you want to execute an instruction five times, it is best to run the for loop syntax rather than typing the same code five times.

New programmers often don’t know how to use the bash for loop, and it is common for amateur programmers to sought to forums to learn how to use bash for loop in Linux? How can one set infinite loops? This article will help coders to understand the best way to use loops expression with basic to advance parameters.

The for loop is often considered as an iteration statement whereby it is a way to repeat a process within a bash script. One can use the for loop statement even within a shell script. While the For Loop is a prime statement in many programming languages, we will focus on how to use it for the bash language.

Are you ready to add yet another tool to your developer arsenal? Let’s explore deeper into the most frequently used tools.

Standard Bash For Loop

Here is an example of how the Bash For Loop takes the form:

for item in [LIST]

do

[COMMANDS]

done

In the above expression, the list can be a series of things that are parted by anything from a range of numbers to an array.

Over Strings

Now let's look at standard Bash for Loop over Strings. For instance, in the below example, the loop will repeat each item in the list of strings and variable element fixed to the current item.

for element in Gold Silver Diamond Platinum

do

echo "Element: $element"

Done

Over a Number Range

Similarly, to define a range of numbers, one can use the sequence expression. To do so, programmers have to designate start and end points of the range. It is expressed in the following form - {START..END}

For instance, let's look at the following example where it will iterate through number starting

from 3 to 7.

for i in {3..7}

do

echo "Number: $i"

done

When using ranges, programmers can also choose to state the increment. The expression would look like this - {START..END..INCREMENT}

for i in {0..20..5}

do

echo "Number: $i"

done

Over Array Elements

While one can use the for loop for numbers and strings, programmers can even leverage the same to repeat over a range. For example, we will state an array - Players and iterate over each of the elements of the range.

PLAYERS=('Cristiano Ronaldo' 'Lionel Messi' 'Iker Casillas')

for player in "${PLAYERS[@]}"; do

echo "Player: $player"

done

Break and Continue for Loop

While the primary purpose of the For Loop is to iterate, you want it to stop repeating and break the loop when a specific condition is met. For that matter, there are independent statements to break and continue the loop. In other words, the break and continue statements is the tool by which programmers can manage the for loop statements.">

Break Statement

As simple as it reads, the break statement is used to end the current for loop. To use the break statement, users have to specify a particular condition when met will break the loop. Programmers can even use the break statement when they want to stop the for loop before planned.

For instance, we use the if statement to terminate the for loop once the current item is the same as ‘Diamond.’

for element in Gold Silver Diamond Platinum; do

if [[ "$element" == 'Diamond' ]]; then

break

fi

echo "Element: $element"

done

echo 'All Done!'

Continue Statement

Similarly, programmers can use the continue statement to first exit the current repetition and then initiates the repetition to the next iteration of the loop. For example, let us use the continue statement to iterate through a range of number and when it reaches a specific number, which in this case will be ‘4’, the continue statement will exit the iteration and go back to the beginning of the loop to begin the next iteration.

for i in {3..7}; do

if [[ "$i" == '4' ]]; then

continue

fi

echo "Number: $i"

done

Examples of Bash for Loops

There are two ways to use the For Loop in bash, one is in the ‘c-style syntax,’ and the other is ‘for-in.’ The syntax for the c-style for loops is as follows:

for ((INITIALIZATION; TEST; STEP))

do

[COMMANDS]

done

Meanwhile, as aforementioned, the ‘for-in’ loop will take the following form:

for variable in list

do

Statements

Done

Let us look at some of the examples of using for loop in Bash now that the syntax is clear.

Example 1 - for Loop to Read Input Variable

Using the for loop, it is straightforward to read the predefined strings or array. Here is an example of how you can use the for loop. In the example, we will take the input value of a text that has multiple words that will be taken after executing the script. We will use the for loop to divide the predefined text based on white space. Then ensure that the script will print each word.

#!/bin/bash

echo "Enter a text of multiple words"

read text

i=1

for word in $text

do

echo "Word No-$i = $word"

((i=$i+1))

done

Then run the following script:

$ bash forloop1.sh

Example 2 - for Loop With a Break Statement

The break statement is used within the ‘for loop’ to end the loop. First, create a file and run the following code. For instance, we will use for loop to read the list of names, and we will test two conditions. The first is if the person's name is ‘Jordan’ and the shape ‘Triangle,’ so in this case, the loop will terminate after it prints the Jordan and Triangle. The for loop for the shape will run until the shape is matched.

for name in Jordan Micheal Smith John Nicolas

do

if [ $name == 'Jordan' ]

then

for shape in Circle Triangle Square Rectangle

do

if [ $shape == "Triangle" ]

then

echo "The favorite shape of $name is $shape"

break

else

echo "The current shape is $shape"

fi

done

fi

done

Example 3 - Reading Files and Directories Using for Loop

Programmers can use the for loop statement to read and print the list of files and folders of the current directory. First, create a file name and execute the following script. Users must note that the ‘*’ is used to read files in the ‘for loop.’ The functioning of the loop is the simple manner by reading each file or folder through the step of the directory and prints with the output in the terminal with the ‘tab’ space.

printf "Pinting the files and folders of the current Directory...\n\n"

for list in *

do

printf "$list\t"

done

printf "\n\nDone\n"

Next, run the below script

$ bash forloop1.sh

Example 4 - Renaming Files With Spaces

Let us see how we can use Bash for loop to rename all files in the current directory that has space. For example, we will replace space in the file name with a percentage sign - %.

for file in *% *; do

mv "$file" "${file// /_}"

done

Now let us understand the above loop statement.

The first line of the expression creates a for loop and repeats it through the list of files that have space in their name. The first expression will generate the list, while the second line subsequently applies the change of name to each file in the list. Therefore, in our example, it will replace the space with a percentage sign. Meanwhile, ‘done’ at the end specifies the end of the loop segment.

Example 5 - Changing File Extension

Using the for loop, one can change the file extension of all files in the current directory. For instance, we will replace all .jpeg with .png file using the for loop.

for file in *.jpeg; do

mv -- "$file" "${file%.jpeg}.png"

done

Similarly, as the above example, the first line will list all files ending with .jpeg extension in the current directory. While the second line will replace .jpeg to .png.

The above is a brief of for loop for Bash. While we only listed a few examples, there are various ways one can use the statement and be more creative and efficient.