While Loops

Execute commands repeatedly while condition is true

Basic while loop

Simple while loop with counter

#!/bin/bash
counter=1
while [ $counter -le 5 ]; do
    echo "Count: $counter"
    counter=$((counter + 1))
done
While loop reading file

Read file line by line

#!/bin/bash
while IFS= read -r line; do
    echo "Processing: $line"
done < "input.txt"
Infinite loop with break

Infinite loop (use with caution)

#!/bin/bash
while true; do
    echo "Press Ctrl+C to exit"
    sleep 1
done
While loop with user input

Interactive loop with user input

#!/bin/bash
while true; do
    read -p "Enter command (quit to exit): " cmd
    if [ "$cmd" = "quit" ]; then
        break
    fi
    echo "You entered: $cmd"
done
While loop with arithmetic operations

While loop using arithmetic evaluation for cleaner syntax

#!/bin/bash
counter=0
while (( counter < 10 )); do
    echo "Count: $counter"
    (( counter++ ))
done
While loop with array iteration

While loop iterating through array elements

#!/bin/bash
fruits=("apple" "banana" "cherry")
i=0
while [ $i -lt ${#fruits[@]} ]; do
    echo "Fruit: ${fruits[$i]}"
    (( i++ ))
done
While loop with user menu

Interactive while loop with menu system

#!/bin/bash
while true; do
    echo "1. Option 1"
    echo "2. Option 2"
    echo "3. Exit"
    read -p "Choose: " choice
    
    case $choice in
        1) echo "You chose option 1" ;;
        2) echo "You chose option 2" ;;
        3) break ;;
        *) echo "Invalid choice" ;;
    esac
done
While loop with timeout

While loop with timeout mechanism

#!/bin/bash
timeout=30
start_time=$(date +%s)

while [ $(($(date +%s) - start_time)) -lt $timeout ]; do
    if some_condition; then
        echo "Condition met!"
        break
    fi
    sleep 1
done
Bash while with command substitution

Bash while loop with process substitution

#!/bin/bash
while read -r line; do
    echo "Processing: $line"
done < <(command_that_outputs_lines)
Bash while with timeout using timeout command

Bash while loop with timeout using timeout command

#!/bin/bash
timeout 30 bash -c '
while true; do
    if some_condition; then
        echo "Condition met!"
        break
    fi
    sleep 1
done
'