Skip to content

Master Bash: 5 Handy For Loop Examples

Master Bash: 5 Handy For Loop Examples

[ad_1]

Introduction

Think about you might have a listing crammed with hundreds of information, and you’ve got been requested to course of these information one after the other. Sounds fairly tedious, proper? Properly not, if you’re utilizing For loops in Bash script. For loop in bash script is a magical instrument that may assist you automate any repetitive job whereas effectively dealing with these information with out breaking a sweat. On this article, we focus on what are for loops in bash with some sensible examples to make automation a toddler’s play.

What’s For Loop in Bash Script

For loop is a management construction that’s used to carry out repetitive duties or execute a bunch of instructions a selected variety of occasions. With for loop, you may iterate by way of numbers, lists, information, and even directories.

Bash For Loop: POSIX Fashion Syntax

The POSIX (Moveable Working System Interface) model syntax can be utilized with POSIX compliant shells like bash and can be utilized to iterate over an inventory of information, any sequence, and even the output of different instructions. Right here is the for loop syntax in bash script:

for <loop_variable> in <list_to_iterate> 
do 
    <Commands_to_be_executed_in_each_iteration>
finished

Within the above syntax:

  • <loop_variable> is a user-defined variable that holds every merchandise from the <list_to_iterate>.
  • <list_to_iterate> refers back to the listing of things over which the for loop is required to iterate. It may be an inventory of numbers, strings, output of a command, and so forth.
  • do key phrase signifies the beginning of the for loop.
  • <Commands_to_be_executed_in_each_iteration> comprises the instructions or statements which will likely be executed for each iteration.
  • finished key phrase signifies the top of the for loop.

Allow us to now see some sensible examples primarily based on the POSIX model for loop:

Instance 1: Loop by way of a Given Vary

#!/bin/bash 

# Print numbers from 1 to five
for i in $(seq 1 5); 
do 
    echo $i 
finished

Within the above snippet, the $(seq 1 5) half is used to generate an inventory of integers from 1 to five. It can then loop over the listing one after the other after which every worth will get printed on a brand new line.

Instance 2: Loop by way of an Array

#!/bin/bash 

fruits=("Apple" "Banana" "Orange" "Grapes") 
for fruit in "${fruits[@]}"; 
do 
    echo "Fruit: $fruit" 
finished

An array is a knowledge construction that’s used to comprise a number of information of various varieties. Within the above snippet:

  • The road fruits=(“Apple” “Banana” “Orange” “Grapes”) is used to declare the array containing 4 totally different fruit names.
  • The road “for fruit in “${fruits[@]}”; do” units up the For Loop. It specifies the variable “fruit” to carry the present ingredient worth and “${fruits[@]}” because the array to be iterated. The “@“, inside “${fruits[@]}“, represents all the weather of the array.
  • The road “echo “Fruit: $fruit” ” prints every fruit identify on a brand new line together with the phrase “Fruit” throughout every iteration.
  • Lastly the final line “finished” signifies the top of the for loop.

Right here is the output we are going to get from the above instructions:

Instance 3: Loop with Command Substitution

#!/bin/bash 

for file in $(ls); 
do 
    echo "File: $file" 
finished

The way in which command substitution works is, the command will get first executed after which the for loop will iterate by way of your entire output of the command. The command to be iterated upon is positioned inside “$()“.

Within the above snippet:

  • Within the line for file in $(ls); do, the $(ls) half executes the ‘ls’ command then and its output (the listing of information within the present listing) is used as enter for the loop. The loop will iterate by way of every file identify discovered within the output.
  • The road echo “File: $file” prints the worth of the “file” variable together with the prefix “File: ” throughout every iteration. The “file” variable comprises the identify of the present file being processed within the loop.
  • Lastly the final line “finished” signifies the top of the for loop.

The output for the for loop with command substitution as demonstrated within the above instance could be:

Bash For Loop: C Fashion Syntax

The C model syntax fits customers who’re extra accustomed to the for loop syntax in different languages like C, C++, Java, JavaScript, and so forth. Right here is the essential syntax to the C model for loop:

for ((<variable_initialization>; <test_condition>; <step_value>)) 
do 
    <commands_to_execute> 
finished

Within the above syntax:

  • <variable_initialization> refers back to the preliminary worth the loop variable will begin from.
  • <test_condition> defines the situation on which the output will rely; this situation is checked in every iteration.
  • <step_value> refers back to the worth by which the loop variable must get up to date.
  • <commands_to_execute> refers back to the instructions or statements that have to be executed for every iteration.

Allow us to now see some sensible examples primarily based on the C model for loop:

Instance 1: Print Odd Numbers from 1 to 10

#!/bin/bash 

for((i = 1; i <= 10; i = i + 1)) 
do 
    if (( i % 2 == 1 )) 
    then 
        echo "Odd Quantity: $i" 
    fi 
finished

Within the above snippet:

  • The road for((i = 1; i <= 10; i = i + 1)) initializes the loop variable to 1, checks if the “worth of i is much less or equals to 10” for each iteration, and at last increments the worth of i by including 1 to the present worth after each iteration.
  • if (( i % 2 == 1 )) checks if the rest worth on dividing the present worth of i with 2 is the same as 1 or not – if divisible, then the road echo “Odd Quantity: $i” will get executed printing the worth of i.
  • the road fi signifies the top of the if situation.
  • Lastly, the final line demarcates the top of the for loop and will get executed on the finish.

Right here is the output you’ll get for the above code:

Instance 2: Loop by way of an Array

#!/bin/bash 

fruits=("Apple" "Banana" "Orange" "Grapes") 
for ((i = 0; i < ${#fruits[@]}; i++)); 
do 
    echo "Fruit $((i+1)): ${fruits[i]}" 
finished

Within the above code:

  • fruits=(“Apple” “Banana” “Orange” “Grapes”) creates an array of all fruit names.
  • for ((i = 0; i < ${#fruits[@]}; i++)) first initializes the loop variable “i” to 0 which is able to act because the index variable for array additionally, and the loop continues so long as “i” is lower than the variety of components within the “fruits” array (denoted by ${#fruits[@]}). The loop increments “i” by 1 in every iteration.
  • Since array indices begin from 0 however we need to show them as ranging from 1, the road echo “Fruit $((i+1)): ${fruits[i]}” prints the worth that is the same as the present index “i” plus 1.
  • Lastly, the final line signifies the top of the for loop

[ad_2]

For extra info, please refer this link