Let’s Understand Bash Loops

Loops are core concept in every programming language. But today i am gone share with you about loops in Bash Language. They are powerful in shell scripting, Also, It is very helpful for repetitive task.

Bash have three types of loops.

Type of Bash Loop

  • For
  • While
  • Until

All this three types have different use cases. Let’s Explore Via Examples.

1. For Loop

Basic Loop

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

C-like for Loop

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

Find Ranges using For Loops

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

# With step size
for i in {5..50..5}; do
    echo "Welcome $i"
done

Continue using For Loops

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

Breaks using For Loops

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

2. While Loop

Basic Loops (Auto Increment)

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

Auto Decrement

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

Forever Loop

while true; do
    # here is some code.
done

Forever (shorthand) Loop

while :; do
    # here is some code.
done

Reading lines Loop

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

3. Until Loop

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

These are the basic and some advance loops. We can edit and modify as much as we can and make it more usable. In up coming article we will discuss about bash options.

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

    Leave a Reply