Skip to content

## 📝 Author

Birat Aryalbirataryal.github.io
Created Date: 2025-06-23
Updated Date: Monday 23rd June 2025 08:16:15
Website - birataryal.com.np
Repository - Birat Aryal
LinkedIn - Birat Aryal
DevSecOps Engineer | System Engineer | Cyber Security Analyst | Network Engineer

🔁 Bash while Loops

The while loop in Bash repeatedly executes a block of commands as long as the condition is true.


📐 Basic Syntax

Bash
while [ condition ]
do
    # commands
done

The condition is checked before each iteration.


✅ Examples

1. Basic Counter Example

Bash
#!/bin/bash
count=1
while [ $count -le 5 ]
do
    echo "Count: $count"
    ((count++))  # increment
done

2. Countdown Timer

Bash
#!/bin/bash
n=5
while [ $n -gt 0 ]
do
    echo "$n..."
    sleep 1
    ((n--))
done
echo "Go!"

3. User Input Until Match

Bash
#!/bin/bash
input=""
while [ "$input" != "yes" ]
do
    echo "Type 'yes' to continue:"
    read input
done
echo "Thanks!"

4. Read a File Line by Line

Bash
#!/bin/bash
file="/etc/passwd"

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

5. Infinite Loop

Bash
#!/bin/bash
while true
do
    echo "Running..."
    sleep 2
done

Stop with Ctrl + C.


🧱 Nested while Loops

Bash
#!/bin/bash
i=1
while [ $i -le 3 ]
do
    j=1
    while [ $j -le 2 ]
    do
        echo "i=$i, j=$j"
        ((j++))
    done
    ((i++))
done

⛔ Exit Conditions

Use break to exit early and continue to skip an iteration.

Example: break

Bash
#!/bin/bash
i=1
while [ $i -le 5 ]
do
    if [ $i -eq 3 ]; then
        break
    fi
    echo "i=$i"
    ((i++))
done

Example: continue

Bash
#!/bin/bash
i=0
while [ $i -lt 5 ]
do
    ((i++))
    if [ $i -eq 3 ]; then
        continue
    fi
    echo "$i"
done

🔐 Safe Practices

  • Quote variables: "$var"

  • Use [[ ... ]] for complex logic

  • Test loops with set -x for debugging