Hi Welcome You can highlight texts in any article and it becomes audio news that you can hear
  • Tue. Nov 26th, 2024

9 Examples of for Loops in Linux Bash Scripts

Byindianadmin

Aug 12, 2022
9 Examples of for Loops in Linux Bash Scripts
fatmawati achmad zaenuri/Shutterstock.com

The versatile Bash for loop does exceptional extra than loop spherical a build different of instances. We listing its many variants so that you simply would possibly perchance exercise them efficiently in your get Linux scripts.

The for Loop

All scripting and programming languages get a draw of handling loops. A loop is a piece of code that you simply certainly must get done many instances. Moderately than form the same build of instructions into your script, time and again, a loop will repeat one piece of code time and again for you.

The Bash for loop is extraordinarily versatile. It goes to work with numbers, phrases, arrays, present line variables, or the output of diversified commands. These are broken-down within the header of the loop. The header dictates what the loop is working with—numbers or strings, as an illustration—and what the cessation condition is that can cessation the looping.

The body of the loop incorporates the code that you simply certainly must get repeated. It holds what you desire the loop to enact. The loop body can occupy any true script present.

A variable referred to as the loop counter or iterator is broken-down to step via a vary of values or a listing of files items. For every loop, the iterator takes on the sign of the next amount, string, or no subject files form the loop is iterating over. This permits the loop to work with the values of each and every of the records items in flip, and even in some cases to manipulate the records items themselves.

Straightforward for Loops

Whenever you occur to’re attempting to write down your first for loop, these easy examples will receive you began.

for Loops the exercise of Numerical Lists

That you just can scuttle a for loop on the present line. This present creates and executes a easy for loop. The iterator is a variable referred to as i. We’re going to construct i to be every of the values within the checklist of numbers, in flip. The body of the loop goes to print that sign to the terminal window. The condition that ends this loop is when i has iterated across the total checklist of numbers.

for i in 1 2 3 4 5; enact echo $i; performed

It’s important to issue right here that the variable i is elevated by one each time the loop spins spherical,  but that’s because the checklist of numbers goes up by one each time.

This checklist of numbers starts at 3 and goes up in steps of two, then arbitrarily leaps to 44.

for i in 3 5 7 9 11 44; enact echo $i; performed

It makes no distinction to the for loop. It starts at one cessation of the checklist and makes exercise of each and every sign in flip, except the entire values within the checklist get been broken-down.

Nor enact the numbers must unruffled be in ascending expose. They would possibly perchance be in any expose.

for i in 3 43 44 11 9; enact echo $i; performed

for Loops The usage of Observe Lists

We are able to unbiased correct as with out problems enact the same with phrases. Duplicate the textual teach material of the script into an editor and build it as “phrase-checklist.sh.”

#!/bin/bash

for phrase in Here's a series of phrasesenact 
  echo $worddone

You’ll must exercise chmod to originate the script executable, and any diversified script you reproduction out of this article. Lawful replace the determine of the script each time you exercise the chmod present.

chmod +x phrase-checklist.sh

Let’s scuttle the script.

./phrase-checklist.sh

Lawful because it did with the numbers, the iterator—in this instance, the variable phrase—works its draw via the checklist of files items except it reaches the cessation of the checklist. The loop body accesses the sign within the phrase variable and so every phrase within the checklist will get processed.

for Loops with Quantity Ranges

Whenever you occur to mandatory a for loop to scuttle 100 instances it would possibly perchance possibly perchance well be an spectacular tiring affair to must form in a series of 100 numbers within the loop header. Quantity ranges relieve you specify the first and closing amount handiest.

This script is “amount-vary.sh.”

#!/bin/bash

for i in {1..10}
enact
  echo "Loop trip:" $i
performed

The amount vary is defined inner curly brackets “{}” with two periods “..” keeping aside the numbers that beginning and cessation the vary. Be definite that you simply don’t consist of any whitespace within the vary definition.

Here is the draw in which it runs:

./amount-vary.sh

That you just can consist of one other amount that defines the step dimension the iterator must unruffled exercise to creep via the numbers within the vary. This script, “amount-range2.sh” will exercise a vary of 0 to 32, and a step dimension of 4.

#!/bin/bash

for i in {0..32..4}
enact
  echo "Loop trip:" $i
performed

The iterator steps via the amount vary in jumps of four.

./amount-range2.sh

for Loops The usage of Filenames

Because we can route of lists of phrases, we can receive our scripts to work with filenames. This script is known as “filenames.sh.”

#!/bin/bash

for file in phrase-checklist.sh amount-vary.sh amount-range2.sh filenames.sh
enact
  ls -lh "$file"
performed

It would possibly perchance possibly possibly perchance well be magnificent pointless to get a script that handiest does what ls can enact, nonetheless it does present guidelines on how to receive entry to filenames inner the loop body.

./filenames.sh

In a same diagram to the exercise of the amount vary, we can exercise a file pattern within the loop header to specify the files we must forever route of. This avoids different typing and diagram we don’t must know upfront the names of the files.

This script is known as “filenames2.sh.” We’ve modified the checklist of filenames with the filename pattern “*.sh” to get the script file on all script files within the unique itemizing.

#!/bin/bash

for file in *.sh
enact
  ls -lh "$file"
performed

Here’s the output.

./filenames2.sh

for Loops The usage of Listing Line Parameters

We are able so as to add some extra flexibility by passing within the filename pattern on the present line. The $* variable represents the total present line parameters handed to the script.

Here is “filenames3.sh.”

#!/bin/bash

for file in $enact
  ls -lh "$file"
performed

We’ll request for filenames that beginning with “n” and get an SH extension.

./filenames3.sh n*.sh

We are able to furthermore pass in lots of pattern at a time.

./filenames3.sh n*.sh .bashrc

The iterator variable file takes on the sign of each and every of the present line parameters. Filename patterns are expanded, and the total filenames are processed within the loop body.

RELATED: Work with Variables in Bash

C-adore for Loops

Bash helps the standard three-time duration for loop, equivalent to those came across within the C programming language. They’re referred to as three-time duration for loops because there are three phrases within the loop header.

  • The preliminary sign of the loop iterator.
  • The test for whether the loop continues or ends.
  • The incrementing—or decrementing—of the iterator.

This script is “c-adore.sh.”

The iterator I is determined to 1 before all the pieces of the loop, and the loop will scuttle for as prolonged as the statement ” i<=10 ” is correct. As quickly as i reaches 11, the for loop will cessation. The iterator is being elevated by one, every revolution of the loop.

#!/bin/bash

for (( i=1; i<=10; i++ ))
do 
  echo "Loop number:" $i
done

Let’s run this script.

./c-like.sh

The C-like for loop permits the easy creation of for loops that have slightly odd requirements. This loop starts at 15, and counts backward in steps of 3. This is “c-like2.sh”

#!/bin/bash

for (( i=15; i>0; i-=3 ))
enact 
  echo "Loop amount:" $i
performed

After we scuttle it, it will unruffled jump backward in steps of three.

./c-like2.sh

Endless for Loops

You would possibly perchance well also exercise this format of for loop to form an endless loop. All you have to enact is recall away the total aspects from the loop header, adore this. Here is “endless.sh.”

#!/bin/bash

for (( ; ; ))
enact
  echo "Press Ctrl+C to cessation..."
  sleep 1
performed

You’ll must hit Ctrl+C to cessation the loop.

./endless.sh

for Loops The usage of Observe Arrays

We are able to with out problems iterate via an array of phrases. We have to form the determine of the array within the loop header, and the iterator will stroll via all entries within the array. Here is “phrase-array.sh.”

#!/bin/bash

distributions=("Ubuntu Fedora Manjaro Arch EndeavourOS Garuda")

for distro in $distributions
enact
  echo $distro
performed

The entire distributions are listed for us.

./phrase-array.sh

The proceed Listing

Whenever you occur to desire the loop to step over a particular entry, test whether the iterator fits that entry and exercise the proceed present. The proceed present abandons the unique trip of the loop. It increments the iterator and starts the next trip of the loop—assuming the entry you would possibly perchance possibly skip over isn’t the closing merchandise within the checklist.

Here is “phrase-array2.sh.” It steps over the “Arch” array entry but processes all diversified array people.

#!/bin/bash

distributions=("Ubuntu Fedora Manjaro Arch EndeavourOS Garuda")

for distro in $distributions
enact
  if [[ "$distro" == "Arch" ]] ;
    then
    proceed
  fi
  echo $distro
performed

“Arch” doesn’t appear within the terminal window.

./phrase-array2.sh

The atomize Listing

The atomize present breaks out of the loop and prevents from now on processing.

Here is “phrase-array3.sh.” It’s the same as the outdated script with proceed modified by atomize.

#!/bin/bash

distributions=("Ubuntu Fedora Manjaro Arch EndeavourOS Garuda")

for distro in $distributions
enact
  if [[ "$distro" == "Arch" ]] ;
    then
    atomize
  fi
  echo $distro
performed

When the iterator incorporates “Arch” the for loop

Learn Extra

Click to listen highlighted text!