Banner of None

Bash scripting tutorials: for loop


Category: Shell Scripting

Date: August 2020
Views: 1.18K


Loops are an important part of any pragramming language, they offer a way to repeat commands or instruction witout repeating lines of code, the for loop comes in diffrent styles in bash scripting

Generally the for loop has the following syntax:

    for var in list
        do
            commands
    done

C style for loop:



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



for loop with basic range:


the following for loop will print numbers from 0 to 10:



for i in {0..10} ; do
    echo $i
done


for loop with range and step:


the following for loop will print the numbers : 0 5 10 15 20, since the step is 5



for i in {0..20..5} ; do
    echo $i
done


We can iterate through the results of a command



for w in $(echo "John Smith Sarah Ashly" ) ; do
    echo "my name is $w"
done



the next for loop will go through html files in a directory and change their extension to php



for f in $(ls dir/*.html) ; do
    mv "$f" "$( basename -s .html $f ).php"
done




1.18K views

Previous Article Next Article

0 Comments, latest

No comments.