1. Home
  2. Bash
  3. Bash Tutorial
  4. Bash – While Loop

Bash – While Loop

While Loop in Bash

Similar to for loop, while loop is also entry restricted loop. It means the condition is checked before executing while loop. While loop is also capable to do all the work as for loop can do.


while [condition]
  //programme to execute

#1. Bash – While Loop Example

For example, the following loop will be executed 5 times and terminated when the value of variable num will be greater than 5.

#2. Bash – Infinite While Loop

Infinite for loops can be also known as a never-ending loop. The following loop will execute continuously until stopped forcefully using CTRL+C.

You can also terminate this loop by adding some conditional exit in the script. So whenever the condition goes true, the loop will exit.

#3. Bash – C-Style While Loop

You can also write while loop in bash scripts similar to while loop c programming language.

#4. Bash – While Loop Read File Content

This is a useful feature provided by while loop to read file content line by line. Using this we can read file line by line and perform some tasks.

The while loop reads one line from the file in one iteration and assigned the value to the variable myvar.

Tags , ,