Back to Homepage
Wednesday 7 August 2024
4

How to loop in Bash

Steps to Loop in Bash

Need to loop in Bash? Follow these easy steps:

1. For Loop:

  • Use a for loop to iterate over a list of items:
#!/bin/bash
     for i in {1..5}
     do
       echo "Iteration $i"
     done

2. While Loop:

  • Use a while loop to repeat commands as long as a condition is true:
#!/bin/bash
     counter=1
     while [ $counter -le 5 ]
     do
       echo "Counter: $counter"
       ((counter++))
     done

3. Until Loop:

  • Use an until loop to repeat commands until a condition becomes true:
#!/bin/bash
     counter=1
     until [ $counter -gt 5 ]
     do
       echo "Counter: $counter"
       ((counter++))
     done

4. Loop Through Array:

  • Iterate over an array with a for loop:
#!/bin/bash
     fruits=("apple" "banana" "cherry")
     for fruit in "${fruits[@]}"
     do
       echo "Fruit: $fruit"
     done
Share:
Created by:
Author photo

Jorge García

Fullstack developer