Learn How to Use Bash For Loop in Shell Scripts

A little promemoria For Loops in Shell Scripts

Bash For Loop with Ranges

#!/bin/bash

for n in {1..7};
do
   echo $n
done
#!/bin/bash

for n in {1..7..2};
do
   echo $n
done

Bash For Loops with Arrays

#!/bin/bash

fruits=("blueberry" "peach" "mango" "pineapple" "papaya") 

for n in ${fruits[@]}; 
do
    echo $n
done

Bash C-styled For Loops

#!/bin/bash

n=7
for (( n=1 ; n<=$n ; n++ )); 
do
    echo $n
done

Use the ‘Continue’ statement with Bash For Loop

#!/bin/bash
for n in {1..10}
do
        if [[ $n -eq '6' ]]
        then
              echo "Target $n has been reached"
              continue
        fi
        echo $n
done

Use the ‘break’ statement with Bash For Loop

#!/bin/bash
for n in {1..10}
do
        if [[ $n -eq '6' ]]
        then
                echo "Target $n has been reached"
                break
        fi
        echo $n
done
echo "All done"

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.