How To Write A “for” Loop Using BASH

You may run bash instructions within a terminal window one after the alternative or you can upload the instructions to a textual content

Bash (which stands for bourne once more shell) is a scripting language used by most linux and unix-based running systems.

You may run bash instructions within a terminal window one after the alternative or you can upload the instructions to a textual content document to supply a shell script.

The great element approximately writing shell scripts is that you could run them over and over. As an example believe you need to add a user to a device, set their permissions and manipulate their beginning surroundings.

You may either write down the commands on a bit of paper and run them as you upload new users or you can write a single script and just skip parameters into that script.

Scripting languages consisting of bash have similar programming constructs as different languages. As an example, you could use import parameters to get enter from the keyboard and store them as variables. You could then get the script to carry out a sure movement primarily based on the cost of the enter parameters.

A key part of any programming and scripting language is the ability to run the same piece of code again and again.

There are a number of methods to repeat code (additionally called loops). On this guide, you may be proven the way to write a “for” loop.

A for loop repeats a positive segment of the code time and again. They’re useful so that a series of commands can keep running until a selected circumstance is met, after which they’ll prevent.

On this guide, you’ll be shown 5 methods to use the for loop within a bash script.

Earlier than getting started

Earlier than you get started out with the for loop examples, you want to open a terminal window and observe these steps:

  • Enter mkdir scripts (study greater approximately mkdir right here)
  • Input cd scripts (this adjustments the listing to scripts)
  • Input nano examplen.Sh (in which n is the instance you’re operating on)
  • Input the script
  • Press ctrl+o to save and ctrl+x to go out
  • Run bash examplen.Sh (again, with n being the example you’re running with)
READ  LINUX - Compress a folder with tar?

How to loop thru a list

for number in 1 2 3 4 5
echo $number
exit 0

The bash way of using “for” loops is truly one-of-a-kind to the manner most other programming and scripting languages deal with “for” loops. Allow’s damage the script down…

In a bash “for” loop all, the statements among do and accomplished are completed once for each object in the listing.

Within the above example, the list is the whole lot that comes after the word in (i.E. 1 2 3 four 5).

Whenever the loop iterates, the subsequent fee within the listing is inserted into the variable precise after the phrase “for”. In the above loop, the variable is referred to as wide variety.

The echo declaration is used to displayed data to the display.

Therefore, this example takes the numbers 1 through five and outputs them separately to the display:

  • 1
  • 2
  • 3
  • 4
  • 5

A way to loop between a begin and stop point

The hassle with the above instance is that in case you want to manner a larger list (say 1 to 500), it might take ages to type all of the numbers within the first vicinity.

This brings us to the second one example which indicates the way to specify a start and quit factor:

for number in {1..10}
echo "$number "
exit 0

The guidelines are basically the equal. The values after the phrase “in” make up the listing to iterate thru and every price inside the list is positioned inside the variable (i.E. Range), and every time the loop iterates, the statements among do and executed are executed.

The principle difference is the way the listing is shaped. The curly brackets essentially denotes a variety, and the variety, in this situation, is 1 to 10 (the two dots separate the start and stop of a range).

READ  How To Fix A Broken USB Drive Using Linux

This example, consequently, runs thru each number among 1 and 10 and outputs the wide variety to the display as follows:

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

The same loop could have been written like this, with syntax identical to the first example:

for number in 1 2 3 4 5 6 7 8 9 10

A way to bypass numbers in a selection

The previous instance showed the way to loop among a begin and stop factor, so now we’re going to take a look at how to bypass numbers inside the range.

Believe you want to loop between 0 and a hundred however only display each tenth variety. The subsequent script shows a way to do simply that:

for number in {0..100..10}
echo "$number "
exit 0

The regulations are basically the same. There is a listing, a variable, and a hard and fast of statements to be accomplished among do and carried out. The list this time looks like this: zero..100..10.

The first range is 0 and the end number is a hundred. The 0.33 wide variety (10) is the range of gadgets inside the list that it will skip.

The above example, therefore, displays the following output:

  • 10
  • 20
  • 30
  • 40
  • 50
  • 60
  • 70
  • 80
  • 90
  • 100

A more traditional looking for loop

The bash way of writing for loops is barely atypical while compared to other programming languages.

You could, however, write a for loop in a similar fashion to the c programming language, like this:

for ((number=1;number < 100;number++))
if (( $number % 5 == 0 ))
echo "$number is divisible by 5 "
exit 0

The loop starts by using placing the variable variety to 1 (number = 1). The loop will preserve iterating even as the cost of a variety of is less than one hundred (quantity < 100). The cost of wide variety adjustments by means of adding 1 to it after every generation (range++).

READ  10 Linux Markdown Editors You Should Try

The whole thing among the curly braces is executed via every iteration of the loop.

The bit between the braces exams the value of various, divides it via 5, and compares the the rest to zero.

If the the rest is zero then the range is divisible by means of 5 and is then displayed on the display.

For example:

  • 5 is divisible by way of 5
  • 10 is divisible by way of 5
  • 15 is divisible by way of 5

In case you need to alternate the step length of the generation you could amend the quantity++ phase to be variety=number+2, variety=range+5, or variety=range+10 and so forth.

This will be further reduced to wide variety+=2 or variety+=five.

A practical instance

For loops can do more than iterate lists of numbers. You can certainly use the output of different commands because the list.

The following instance suggests the way to convert audio documents from mp3 to wav:


for file in ./*.mp3
mpg -w ./wavs/"${file}".wav "$file"

The listing in this example is every record with the .Mp3 extension within the current folder and the variable is a file.

The mpg command converts the mp3 document into wav. But, you probably want to install this the usage of your package manager first.

About the author

Wikitechy Editor

Wikitechy Editor

Wikitechy Founder, Author, International Speaker, and Job Consultant. My role as the CEO of Wikitechy, I help businesses build their next generation digital platforms and help with their product innovation and growth strategy. I'm a frequent speaker at tech conferences and events.

Add Comment

Click here to post a comment