Banner of d1c7067295d728168bd8.jpg

Bash scripting tutorials: for loop


Category: Shell Scripting

📅 August 22, 2020   |   👁️ Views: 30

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




← Creating A Real Website with PHP object oriented - part 4 - Autoload and Register Classes Creating A Real Website with PHP Object Oriented part 5 URL Handling, Views and website behavior →