Bash Loops

Reading lines

cat file.txt | while read line; do
    echo $line
done

Forever (shorthand)

while :; do
    # here is some code.
done

Forever

while true; do
    # here is some code.
done

Until

count=0
until [ $count -gt 10 ]; do
    echo "$count"
    ((count++))
done

Break

for number in $(seq 1 3); do
    if [[ $number == 2 ]]; then
        # Skip entire rest of loop.
        break;
    fi
    # This will only print 1
    echo "$number"
done

Continue

for number in $(seq 1 3); do
    if [[ $number == 2 ]]; then
        continue;
    fi
    echo "$number"
done

Auto decrement

i=3
while [[ $i -gt 0 ]]; do
    echo "Number: $i"
    ((i--))
done

Auto increment

i=1
while [[ $i -lt 4 ]]; do
    echo "Number: $i"
    ((i++))
done

Ranges

for i in {1..5}; do
    echo "Welcome $i"
done

#With step size

for i in {5..50..5}; do
    echo "Welcome $i"
done

C-like for loop

for ((i = 0 ; i < 100 ; i++)); do
    echo $i
done

Basic for loop

for i in /etc/rc.*; do
    echo $i
done
Comments