Bash While Loop


Bash While Loop

In Bash scripting, the while loop allows you to repeatedly execute a block of commands as long as a specified condition is true.


Syntax

while [ condition ]; do
    # commands
done

The basic syntax involves using while followed by a condition in square brackets, the commands to execute while the condition is true, and the loop ends with done.


Example Bash While Loops

Let's look at some examples of how to use while loops in Bash:

1. While Loop to Print Numbers

This script uses a while loop to print numbers from 1 to 5.

#!/bin/bash

count=1

while [ $count -le 5 ]; do
    echo "Count: $count"
    ((count++))
done

In this script, the variable count is initialized to 1. The while loop checks if count is less than or equal to 5 using the -le operator. If true, it prints the value of count and increments count by 1.

While loop to print numbers in Bash

2. While Loop to Read User Input

This script uses a while loop to repeatedly ask the user for input until they type 'exit'.

#!/bin/bash

input=""

while [ "$input" != "exit" ]; do
    read -p "Enter something (type 'exit' to quit): " input
    echo "You entered: $input"
done

In this script, the variable input is initialized to an empty string. The while loop checks if input is not equal to 'exit' using the != operator. If true, it prompts the user to enter something and prints the entered value. The loop continues until the user types 'exit'.

While loop to read user input in Bash

3. While Loop to Read a File Line by Line

This script uses a while loop to read a file line by line and print each line.

#!/bin/bash

filename="example.txt"

while IFS= read -r line; do
    echo "$line"
done < "$filename"

In this script, the variable filename is assigned the name of the file to read. The while loop reads the file line by line using the read command and prints each line. The loop continues until all lines are read.

While loop to read a file line by line in Bash

Conclusion

The Bash while loop is a crucial tool for tasks that require repeated execution until a condition changes in shell scripting. Understanding how to use while loops can help you automate and simplify many tasks in your scripts.