# Using While Loop in Bash

Loops are programming constructs that continuously execute specific commands unless interrupted, and the `while` loop in Bash is a control structure that runs commands for as long as a condition evaluates to `true`. You can use `while` loops to handle user input, read files, and run a series of commands continuously. This guide covers the `while` loop syntax and walks through building basic, infinite, and nested loops, controlling loop flow with `break` and `continue`, and combining `while` loops with conditional statements and functions. By the end, you'll have a set of working `while` loop scripts that read files, repeat indefinitely, and respond to different conditions, following Bash looping practices documented in [**Vultr Docs**](https://docs.vultr.com/how-to-use-while-loop-in-bash).

---

## 1\. Learn the while Loop Syntax

The `while` loop in Bash follows this syntax:

```plaintext
while [CONDITION]
do
   # Commands
done
```

- `while`: starts the loop.
- `condition`: the condition you want to evaluate.
- `do`: marks the beginning of the loop body, including the commands to run when the condition evaluates to `true`.
- `done`: marks the end of the loop and stops execution when the condition evaluates to `false`.

## 2\. Create while Loops in Bash

**1\. Create an inline** `while` **loop that increments a numeric variable up to** `10`**:**

```console
x=0; while [ $x -le 10 ]; do echo "The value of X is: $x"; ((x++)); done
```

Output:

```plaintext
The value of X is: 0
The value of X is: 1
The value of X is: 2
The value of X is: 3
The value of X is: 4
The value of X is: 5
The value of X is: 6
The value of X is: 7
The value of X is: 8
The value of X is: 9
The value of X is: 10
```

The `$x -le 10` condition evaluates to `true` while `x` is less than or equal to `10`, printing its current value and incrementing it with `((x++))` on each pass. Inline `while` loops let you run conditions directly in the shell without creating a script, which is useful for evaluating files or capturing real-time user input.

**2\. Create a new** `while.sh` **script that prints a variable's value while it's less than** `10`**:**

```console
nano while.sh
```

**3\. Add the following contents to the** `while.sh` **file:**

```bash
#!/bin/bash
var=0

while [ $var -lt 10 ]
do
  echo The current value: $var is less than 10
  ((var++))
done
```

Save and close the file.

**4\. Run the script using Bash:**

```console
bash while.sh
```

Output:

```plaintext
The current value: 0 is less than 10
The current value: 1 is less than 10
The current value: 2 is less than 10
The current value: 3 is less than 10
The current value: 4 is less than 10
The current value: 5 is less than 10
The current value: 6 is less than 10
The current value: 7 is less than 10
The current value: 8 is less than 10
The current value: 9 is less than 10
```

**5\. Create a new** `while-script.sh` **script:**

```console
nano while-script.sh
```

**6\. Add the following contents, using input redirection (**`<`**) instead of a condition to read a file line by line:**

```bash
#!/bin/bash

while IFS= read -r line; do
    echo "$line"
done < "/etc/passwd"
```

Save and close the file. The `while` loop uses the `<` redirection to feed the `/etc/passwd` file into the `read` command and iterate over every line; the `IFS=` option preserves whitespace in the file.

**7\. Run the script using Bash:**

```console
bash while-script.sh
```

Output:

```plaintext
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
sys:x:3:3:sys:/dev:/usr/sbin/nologin
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/usr/sbin/nologin
man:x:6:12:man:/var/cache/man:/usr/sbin/nologin
lp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologin
mail:x:8:8:mail:/var/mail:/usr/sbin/nologin
news:x:9:9:news:/var/spool/news:/usr/sbin/nologin
uucp:x:10:10:uucp:/var/spool/uucp:/usr/sbin/nologin
proxy:x:13:13:proxy:/bin:/usr/sbin/nologin
```

## 3\. Create an Infinite while Loop

Infinite `while` loops run indefinitely as long as their condition evaluates to `true`, unless terminated or interrupted. The `:` command creates a condition that's always true, which is useful for logging and monitoring tasks that output continuous data.

**1\. Create a new** `infinite.sh` **script:**

```console
nano infinite.sh
```

**2\. Add the following contents to the** `infinite.sh` **file:**

```bash
#!/bin/bash

while :
do
  echo "This is an Infinite loop message, press <CTRL + C> to stop"
  sleep 1
done
```

Save and close the file. The `:` option creates an infinite loop that prints the message every second, thanks to the `sleep 1` command.

**3\. Run the script using Bash (stop it with** `<CTRL + C>`**):**

```console
bash infinite.sh 
```

Output:

```plaintext
This is an Infinite loop message, press <CTRL + C> to stop
This is an Infinite loop message, press <CTRL + C> to stop
This is an Infinite loop message, press <CTRL + C> to stop
This is an Infinite loop message, press <CTRL + C> to stop
This is an Infinite loop message, press <CTRL + C> to stop
```

## 4\. Create Nested while Loops

Nested `while` loops run a loop inside another loop to handle more complex iterative tasks.

**1\. Create a new** `nested.sh` **script:**

```console
nano nested.sh
```

**2\. Add the following contents to the** `nested.sh` **file:**

```bash
#!/bin/bash

app_name=("Apache" "Mysql" "Nginx" "Mysql" "PHP")

var=0
while [ $var -lt ${#app_name[@]} ]; do
    j=0
    while [ $j -lt ${#app_name[@]} ]; do
        if [ $var -ne $j ]; then
            echo "Pair: ${app_name[$var]} and ${app_name[$j]}"
        fi
        ((j++))
    done
    ((var++))
done
```

Save and close the file. The outer `while` loop iterates over every element in the `app_name` array, and the inner loop pairs each entry with every other non-identical entry, using the `j` variable to track position.

**3\. Run the script using Bash:**

```console
bash nested.sh 
```

Output:

```plaintext
Pair: Apache and Mysql
Pair: Apache and Nginx
Pair: Apache and Mysql
Pair: Apache and PHP
Pair: Mysql and Apache
Pair: Mysql and Nginx
Pair: Mysql and Mysql
Pair: Mysql and PHP
Pair: Nginx and Apache
Pair: Nginx and Mysql
Pair: Nginx and Mysql
Pair: Nginx and PHP
Pair: Mysql and Apache
Pair: Mysql and Mysql
Pair: Mysql and Nginx
Pair: Mysql and PHP
Pair: PHP and Apache
Pair: PHP and Mysql
Pair: PHP and Nginx
Pair: PHP and Mysql
```

To control the flow of a `while` loop, conditional statements like `if-else` are essential — see the [if-else in Bash guide](https://docs.vultr.com/how-to-use-the-if-else-statement-in-bash) for more.

## 5\. Use the break Statement in a while Loop

The `break` statement terminates and exits a loop as soon as a condition evaluates to `true`.

**1\. Create a new** `break.sh` **script:**

```console
nano break.sh
```

**2\. Add the following contents to the** `break.sh` **file:**

```bash
#!/bin/bash

var=0

while [ $var -lt 10 ]
do
  echo "Updated Value is: $var"
  ((var++))
  if [[ "$var" == '10' ]]; then
    echo "The value is equal to 10, ending..."
    break
  fi
done

echo 'The loop test is complete!'
```

Save and close the file. The `break` statement terminates the loop once `var` reaches `10` and the script then prints the closing message.

**3\. Run the script using Bash:**

```console
bash break.sh
```

Output:

```plaintext
Updated Value is: 0
Updated Value is: 1
Updated Value is: 2
Updated Value is: 3
Updated Value is: 4
Updated Value is: 5
Updated Value is: 6
Updated Value is: 7
Updated Value is: 8
Updated Value is: 9
The value is equal to 10, ending...
The loop test is complete!
```

## 6\. Use the continue Statement in a while Loop

The `continue` statement stops the current iteration and starts the next one once a condition evaluates to `true`, without ending the loop itself.

**1\. Create a new** `continue.sh` **script:**

```console
nano continue.sh
```

**2\. Add the following contents to the** `continue.sh` **file:**

```bash
#!/bin/bash

var=0

while [ $var -lt 10 ]
do
  echo "Updated Value is: $var"
  ((var++))
  if [[ "$var" == '5' ]]; then
    echo "The value is equal to 5, skipping..."
    continue
  fi
done
```

Save and close the file. The `if` statement checks whether the current value equals `5`; when it does, `continue` immediately starts the next iteration and skips any remaining commands in the loop body.

**3\. Run the script using Bash:**

```console
bash continue.sh
```

Output:

```plaintext
Updated Value is: 0
Updated Value is: 1
Updated Value is: 2
Updated Value is: 3
Updated Value is: 4
The value is equal to 5, skipping...
Updated Value is: 5
Updated Value is: 6
Updated Value is: 7
Updated Value is: 8
Updated Value is: 9
```

## 7\. Use while Loops with Conditional Statements

You can combine conditional statements (`if`, `case`, or `if-else`) with `break` and `continue` to use a loop's results to drive its flow.

**1\. Create a new** `if-while.sh` **script:**

```console
nano if-while.sh
```

**2\. Add the following contents to the** `if-while.sh` **file:**

```bash
#!/bin/bash

var=0

while [ $var -le 10 ]; do
    if (( var % 2 == 0 )); then
        echo "The value of $var is EVEN."
    else
        echo "The value of $var is ODD."
    fi

    ((var++))
done
```

Save and close the file. The `if-else` statement inside the loop checks whether `var` is divisible by `2` to decide if its value is even or odd.

**3\. Run the script using Bash:**

```console
bash if-while.sh
```

Output:

```plaintext
The value of 0 is EVEN.
The value of 1 is ODD.
The value of 2 is EVEN.
The value of 3 is ODD.
The value of 4 is EVEN.
The value of 5 is ODD.
The value of 6 is EVEN.
The value of 7 is ODD.
The value of 8 is EVEN.
The value of 9 is ODD.
The value of 10 is EVEN.
```

## 8\. Use while Loops with Functions

You can use `while` loops with functions to reuse code and perform different tasks for each condition.

**1\. Create a new** `functions-while.sh` **script:**

```console
nano functions-while.sh
```

**2\. Add the following contents to the** `functions-while.sh` **file:**

```bash
#!/bin/bash

read -p "Enter your application names (apache,nginx,mysql,php or help|-h): " -a app_name

help_page() {
    echo "Usage: ./functions-while.sh [options]"
    echo
    echo "Options:"
    echo "apache"
    echo "nginx"
    echo "mysql"
    echo "php"
    echo "  -h, --help       Display this help page"
}

var=0

while [ $var -lt ${#app_name[@]} ]; do
    service="${app_name[$var]}"

    if [[ $service == "help" || $service == "-h" ]]; then
        help_page
    else
        case $service in
            "apache")
                echo "$service: works as the Web server"
                ;;
            "mysql")
                echo "$service: works as a Database server"
                ;;
            "nginx")
                echo "$service: works as a Reverse proxy or Web server"
                ;;
            "php")
                echo "$service: works as a Hypertext processor"
                ;;                
            *)
                echo "$service: Unknown service"
                ;;
        esac
    fi

    ((var++))
done
```

Save and close the file. The `app_name` array stores the words from the user's input, and the `while` loop iterates over each element that's less than the `var` variable's value. An `if` statement checks whether the current item is `help`, otherwise a `case` statement matches it against a known service name; `((var++))` advances to the next array element.

**3\. Run the script using Bash:**

```console
bash functions-while.sh
```

Enter one or more application names, such as `apache` or `mysql`, when prompted:

```plaintext
Enter your application names (apache,nginx,mysql,php or help|-h): apache mysql
apache: works as the Web server
mysql: works as a Database server
```

## Next Steps

- Combine `while` loops with arrays to process lists of dynamic data.
- Use a `while` loop to monitor a log file or process in real time.
- Explore `for` loops as an alternative when you know the number of iterations in advance.
- Add input validation with conditional statements to make your loops more robust.

For the full guide with additional tips, visit the original article on [**Vultr Docs**](https://docs.vultr.com/how-to-use-while-loop-in-bash).
