While Loop in Bash

While Loop in Bash

While Loop in Bash


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

Syntax:

while [condition]
do
  //programme to execute
done

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 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 the while loop to read file content line by line. Using this we can read files line by line and perform some tasks.

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

Reactions

Post a Comment

0 Comments

close