While Loop

Bash Scripting While Loop Examples

While Loops


The Bash while loop is used to repeat a section of commands based on a condition. A while loop can also be an infinite loop. Below are examples of while loops:

Basic Syntax of a while loop:




while [ condition ]
do
commands..
commands..
done

In the above example, the commands will be continually executed until the condition becomes false:

Basic example of a while loop:



#!/bin/bash
#
count=1
while [ $count -le 5 ]
do
  printf "Count has a value of $count\n"
  ((count++))
done

In the above while loop example, we initially set our variable $count to a value of "1". While variable $count is less than "5" our print statement will be executed. The variable $count is also incremented ((count++)). All commands that are to be executed are placed between the "do" and "done" statements.

Output from above while loop script:



john@john-desktop:~/scripts$ ./while1.sh 
Count has a value of 1
Count has a value of 2
Count has a value of 3
Count has a value of 4
Count has a value of 5


Reversing the count of a while loop


As we saw in the above example we can control the number of times our loop is executed by using a simple count variable. If you need to reverse your count you would create a script similar to the following example:

Example of a while loop:



#!/bin/bash
#
count=5
while [ $count -gt 0 ]
do
  printf "Count has a value of $count\n"
  ((count--))
done

In the above example we will repeat our print statement while our our $count variable has a value greater than "0". We decrement our $count variable by "1" with the command ((count--)).

Output from above while loop script:



john@john-desktop:~/scripts$ ./while2.sh 
Count has a value of 5
Count has a value of 4
Count has a value of 3
Count has a value of 2
Count has a value of 1


Infinite while loop


An infinite while loop simply continues to execute the code within the "do" and "done" sections. An example of an infinite while loop is below. As the loop will run forever, you will need to press "Ctrl + C" to exit the running script:

Example of an infinite while loop:



#!/bin/bash
#
count=1
while :
do
  printf "Count has a value of $count\n"
  ((count++))
done

Output from above infinite while loop script:



Count has a value of 1
Press Ctrl + C to exit infinite loop
Count has a value of 2
Press Ctrl + C to exit infinite loop
Count has a value of 3
Press Ctrl + C to exit infinite loop
Count has a value of 4
Press Ctrl + C to exit infinite loop
Count has a value of 5
Press Ctrl + C to exit infinite loop
Count has a value of 6
Press Ctrl + C to exit infinite loop