Bash For and While Loop Examples – POFTUT

Bash For and While Loop Examples

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

Loop Syntax

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



For line provides the loop logic and take a 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 usages of the loop is looping through items. We will provide 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  Awk Print Tutorial With Examples

echo '

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

Increment Value

We can also specify the increment number. Incrementing one by one is the 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 statement like the C programming language. We will set stat numbers, end condition and increment value like below. Here is the syntax

Now we will start at 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 the process.

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

Infinite While Loop

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

Just provide a true statement to the while.

LEARN MORE  What Is Unix?

Loop Through Files

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

Loop Through Files

Loop Through Files

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

1 Response

  1. 28/01/2018

    […] Bash For Loop Examples […]

Leave a Reply

Your email address will not be published. Required fields are marked *