How to use a while loops in Linux

Home > Search > How-to
  by

A while loop can is used to iterate through a loop while a certain contain is true.

  • Line 2 creates a variable named foo that contains a value of 1
  • Line 3 creates the while loop with a condition that the commands inside the while loop should execute as long as foo is less than or equal to 5
  • Line 4 starts the loop
  • Line 5 echo's the variable named foo
  • Line 6 increments the variable named foo by 1
  • Line 7 ends the loop
#!/bin/bash
foo=1
while [ $foo -le 5 ]
do
  echo "$foo"
  foo=$(( $foo + 1 ))
done

 

In this example, the while loop will produce this output.

1
2
3
4
5

 


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?
>

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




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




Comments