Bootstrap FreeKB - Bash (Scripting) - while loops
Bash (Scripting) - while loops

Updated:   |  Bash (Scripting) articles

A while loop can be used to iterate through a loop while a certain contain is met. In this example, the value of the $foo variable will be echoed until the the value is less than or equal to 5

#!/bin/bash
foo=0
while [ $foo -le 5 ]
do
  echo "$foo"
  foo=$(( $foo + 1 ))
done

 

The following should be returned.

0
1
2
3
4
5

 

As a bit of a more practical example, a while loop is often used along with an if statement and the ps command to determine if a certain process is or is not running. The while loop with sleep 1 make it so that the while loop is only executed for 30 seconds, in this example.

#!/bin/bash
foo=0
while [ $foo -lt 30 ]
do
  if [[ `ps -ef` = *bar* ]]; then
    echo "The bar process is running"
    break;
  else
    echo "The bar process is NOT running. Will check again in 1 second"
    foo=$(( $foo + 1 ))
  fi
  sleep 1
done

 


Select in while

One of the most useful features of a while loop is to be able to prompt a user for input, and to then ask the user if they are good, or if they need to be prompted again. To accomplish this, a select loop is nested inside of a while loop.

#!/bin/bash

foo=1
fruit=(banana orange apple grape)

while [ $foo -eq 1 ]
do
    echo "Select your favorite fruit"
    select myFruit in "${fruit[@]}"
    do
        read -rep $'Do you want to select another piece of fruit?\n>' answer
        if [ $answer == "yes" ]
        then
            echo "You selected" $myFruit
        else
            echo "All done"
       
            # When $answer is not yes, we set foo to 0 to end the while loop
            foo=0
        fi

    # When we have nested statements inside of while, we must break out of the loop
    break
    done
done

 

When the above script is run, you will first be prompted to select your favorite fruit.

Select your favorite fruit
1) banana
2) orange
3) apple
4) grape
#

 

After selecting your favorite fruit, you will be asked if you want to select another piece of fruit. If you type yes, you will be asked to select another piece of fruit. If you type anything other than yes, "all done" will be displayed.

Do you want to select another piece of fruit?
>

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 7660c1 in the box below so that we can be sure you are a human.