Skip to content

While Loop Wizardry in Bash Scripting

Embark on a journey to master the while loop in Bash scripting with this detailed guide. Whether you're iterating over arrays, processing command output, or implementing robust input validation, this guide covers it all. Discover the magic of while loops for effective script automation and control, with practical examples to enhance your Bash scripting prowess.


Numeric Range
i=1
while ((i <= 10)); do
    # Loop body
    echo $i
    ((i++))
done
Iterating over an Array
my_array=("apple" "banana" "orange")
i=0
while ((i < ${#my_array[@]})); do
    # Loop body
    echo ${my_array[i]}
    ((i++))
done
Reading Lines from a File
while IFS= read -r line; do
    # Loop body
    echo $line
done < input.txt
Command Output
ls_output=$(ls)
i=0
while ((i < ${#ls_output[@]})); do
    # Loop body
    echo ${ls_output[i]}
    ((i++))
done
Conditional Looping
while true; do
    # Loop body
    # Condition to break the loop
    if [[ condition ]]; then
        break
    fi
done
Input Validation
valid_input=false
while [[ $valid_input == false ]]; do
    read -p "Enter a number: " num
    # Validation condition
    if [[ condition ]]; then
        valid_input=true
    else
        echo "Invalid input. Please try again."
    fi
done
Infinite Loop with Break
while true; do
    # Loop body
    # Condition to break the loop
    if [[ condition ]]; then
        break
    fi
done