Bash For and While Loop Examples

RSS
EMAIL
FACEBOOK
FACEBOOK
GOOGLE
GOOGLE
https://www.poftut.com/bash-for-and-while-loop-examples/
PINTEREST
PINTEREST
INSTAGRAM

Bash can provides different programming language structures like variable, array, loop, decision making etc. Loop is one of the most useful feature of bash scripting. Loops will give the ability to iterate over given sequential structures like array, file list, numbers, inputs etc.

Loop Syntax

Bash provides alternative syntax for loop. Below are some examples of for loop syntax.

OR

OR

For line provides the loop logic and take step for each number or file or command output

Lines between do and done is the part which will run each step.

Loop Items

One of the most popular usage of loop is looping through items. We will provides items by separating them with space. All items will be looped. In this example we will use numbers from 1 to 7 and define them one by one.

Loop Numbers

Loop ITems

Loop Range

We can loop numbers like above but the problem is how can we achieve if need to loop over 1000 numbers. Should we write the one by one? No we can specify number ranges like below..

LEARN MORE  How To Setup GUI Like Gnome, KDE, Xfce, Unity For Ubuntu Server and Desktop?

We use {1..7} to loop from 1 to 7 one by one.

Increment Value

We can also specify increment number. Incrementing one by one is default behavior. How can we increment 2?

Increment Value

Increment Value

We have incremented loop 2 and only used numbers 1,3,5 . There is an alternative way to increment for loop with 43 for statement

C Style For Loop

We can specify a for statement like C programming language. We will set stat numbers, end condition and increment value like below. Here is the syntax

Now we will start from 1 and increment one by one to the 5.

C Style For Loop

C Style For Loop

Infinite For Loop

We can create a loop for infinity. This loop will run forever if we do not end process.

We do not provide any start number , end condition or increment value to trigger infinite loop.

Infinite While Loop

We can create infinite loop with while statement. Creating infinite loop while statement is more easy.

Just provide true statement to the while.

LEARN MORE  How To Set Get and Change Bash Environment Variable?

Loop Through Files

One of the most used type of loop is looping through files in specified directory. All file names in the specified directory will be looped step by step.

Loop Through Files

Loop Through Files

Here the $(ls -l) provides list of filenames to loop and each file names is assigned to the file variable for each step.

RSS
EMAIL
FACEBOOK
FACEBOOK
GOOGLE
GOOGLE
https://www.poftut.com/bash-for-and-while-loop-examples/
PINTEREST
PINTEREST
INSTAGRAM

You may also like...

Leave a Reply

Your email address will not be published.

Enjoy this blog? Please spread the word :)