🚀 DevOps & SRE Certification Program 📅 Starting: 1st of Every Month 🤝 +91 8409492687 🔍 Contact@DevOpsSchool.com

Upgrade & Secure Your Future with DevOps, SRE, DevSecOps, MLOps!

We spend hours on Instagram and YouTube and waste money on coffee and fast food, but won’t spend 30 minutes a day learning skills to boost our careers.
Master in DevOps, SRE, DevSecOps & MLOps!

Learn from Guru Rajesh Kumar and double your salary in just one year.


Get Started Now!

Shell Scripting Tutorials: Looping & Iteration statatement using for loop



Loops are a programming construct which allow us to repeat a command or set of commands for each item in a list. As such they are key to productivity improvements through automation. Similar to wildcards and tab completion, using loops also reduces the amount of typing required (and hence reduces the number of typing mistakes).

Syntax of For Loop

Example of For Loop

There are some key points of ‘for loop’ statement:

  • Each block of ‘for loop’ in bash starts with ‘do’ keyword followed by the commands inside the block. The ‘for loop’ statement is closed by ‘done’ keyword.
  • The number of time for which a ‘for loop’ will iterate depends on the declared list variables.
  • The loop will select one item from the list and assign the value on a variable which will be used within the loop.
  • After the execution of commands between ‘do’ and ‘done’, the loop goes back to the top and select the next item from the list and repeat the whole process.
  • The list can contain numbers or string etc. separated by spaces.

How For Loop works?

Write Simple Shell Script using For Loop


#!/bin/bash
for i in 1 2 3 4 5
do
 echo "Hello $i"
done

Let’s inspect each element:

  • #!/bin/bash – shows that the code is a bash script
  • i – is a placeholder for a variable. Meanwhile, $i is the individual value of the variable. You can also write it as c/$c or by any other name
  • in – separates the variable and the items that follow
  • 1 2 3 4 5 –  is an example of items you want to perform the instruction on
  • do – is the keyword that starts the loops. It will then execute the instruction n times, with n being the total number of items. Here, the value of n is 5
  • echo “Hello: $i” – is the code which we will repeat n times. Remember quotation marks turn anything inside it into one variable.
  • done – stops the loop

Example Program

# ##########################################################################################
# Program - 1
# ##########################################################################################
#!/bin/bash
for i in 1 2 3 4 5
do
echo "Hello $i"
done
# ##########################################################################################
# Program - 2
# ##########################################################################################
# Using Bash For Loop to Create an Infinity Loop
#!/bin/bash
for (( ; ; ))
do
echo "Hello World"
done
# ##########################################################################################
# Program - 3
# ##########################################################################################
# Using Bash for Loop to Create The Skip and Continue Loop
for I in 1 2 3 4 5
do
if [condition]
then
continue #Continue with the next iteration of I and skip statement 3
fi
statement
done
# ##########################################################################################
# Program - 4
# ##########################################################################################
for city in Alabama Alaska Arizona Arkansas California
do
if [[ "$state" == 'Arkansas' ]]; then
break
fi
echo "state: $state"
done
echo 'That’s all!'
# ##########################################################################################
# Program - 5
# ##########################################################################################
for ((i = 0 ; i <= 1000 ; i++)); do
echo "Counter: $i"
done
# ##########################################################################################
# Program - 6
# ##########################################################################################
# break Statement
# The break statement terminates the current loop and passes program control to the statement that follows the terminated statement. It is usually used to terminate the loop when a certain condition is met.
for element in Hydrogen Helium Lithium Beryllium; do
if [[ "$element" == 'Lithium' ]]; then
break
fi
echo "Element: $element"
done
echo 'All Done!'
# ##########################################################################################
# Program - 7
# ##########################################################################################
# continue Statement
# The continue statement exits the current iteration of a loop and passes program control to the next iteration of the loop.
for i in {1..5}; do
if [[ "$i" == '2' ]]; then
continue
fi
echo "Number: $i"
done
# ##########################################################################################
# Program - 8
# ##########################################################################################
# The following example shows how to rename all of the files in the current directory with a space in its names by replacing space to underscore:
for file in *\ *; do
mv "$file" "${file// /_}"
done
# ##########################################################################################
# Program - 9
# ##########################################################################################
for file in *.jpeg; do
mv -- "$file" "${file%.jpeg}.jpg"
done
# ##########################################################################################
# Program - 10
# ##########################################################################################
#!/bin/bash
# For loop with range increment numbers
for i in {0..10..2}
do
echo "Element $i"
done
# ##########################################################################################
# Program - 11
# ##########################################################################################
#!/bin/bash
# For loop with reverse range increment numbers
for i in {10..0..2}
do
echo "Element $i"
done
# ##########################################################################################
# Program - 12
# ##########################################################################################
# The seq command generates a number sequence. Parse the sequence in the Bash script for loop as a command to generate a list.
#!/bin/bash
# For loop with seq command
for i in $(seq 0 2 10)
do
echo "Element $i"
# ##########################################################################################
# Program - 13
# ##########################################################################################
# Bash scripts allow C-style three parameter for loop control expressions. Add the expression between double parentheses as follows:
#!/bin/bash
# For loop C-style
for (( i=0; i<=5; i++ ))
do
echo "Element $i"
done
# ##########################################################################################
# Program - 14
# ##########################################################################################
# Infinite for loops do not have a condition set to terminate the loop. The program runs endlessly because the end condition does not exist or never fulfills.
#!/bin/bash
# Infinite for loop
for (( ; ; ))
do
echo "CTRL+C to exit"
done
# ##########################################################################################
# Program - 15
# ##########################################################################################
# The break statement ends the current loop and helps exit the for loop early. This behavior allows exiting the loop before meeting a stated condition.
#!/bin/bash
# Infinite for loop with break
i=0
for (( ; ; ))
do
echo "Iteration: ${i}"
(( i++ ))
if [[ i -gt 10 ]]
then
break;
fi
done
echo "Done!"
# ##########################################################################################
# Program - 16
# ##########################################################################################
# The continue command ends the current loop iteration. The program continues the loop, starting with the following iteration. To illustrate, add the following code to a Bash script to see how the continue statement works in a for loop:
#!/bin/bash
# For loop with continue statement
for i in {1..100}
do
if [[ $i%11 -ne 0 ]]
then
continue
fi
echo $i
done
# ##########################################################################################
# Program - 17
# ##########################################################################################
# Arrays store a list of elements. The for loop provides a method to go through arrays by element.
#!/bin/bash
# For loop with array
array=(1 2 3 4 5)
for i in ${array[@]}
do
echo "Element $i"
done
# ##########################################################################################
# Program - 18
# ##########################################################################################
# When working with arrays, each element has an index.
#!/bin/bash
# For loop with array indices
array=(1 2 3 4 5)
for i in ${!array[@]}
do
echo "Array indices $i"
done
# ##########################################################################################
# Program - 19
# ##########################################################################################
# To loop through or generate multi-dimensional arrays, use nested for loops.
#!/bin/bash
# Nested for loop
for (( i = 0; i <= 2; i++ ))
do
for (( j = 0 ; j <= 9; j++ ))
do
echo -n " $i.$j "
done
echo ""
done
# ##########################################################################################
# Program - 20
# ##########################################################################################
# To loop through words in a string, store the string in a variable. Then, parse the variable to a for loop as a list.
#!/bin/bash
# For loop with string
strings="I am a string"
for i in ${strings}
do
echo "String $i"
done
# ##########################################################################################
# Program - 21
# ##########################################################################################
The for loop combined with proximity searches helps list or alter files that meet a specific condition.
#!/bin/bash
# For loop with files
for f in *.sh
do
echo $f
done
# ##########################################################################################
# Program - 22
# ##########################################################################################
# The for loop accepts command substitution as a list of elements to iterate through.
#!/bin/bash
# For loop with command substitution
list=`cat list.txt`
# Alternatively, use list=$(cat list.txt)
for i in $list
do
echo $i
done
Subscribe
Notify of
guest


0 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments

Certification Courses

DevOpsSchool has introduced a series of professional certification courses designed to enhance your skills and expertise in cutting-edge technologies and methodologies. Whether you are aiming to excel in development, security, or operations, these certifications provide a comprehensive learning experience. Explore the following programs:

DevOps Certification, SRE Certification, and DevSecOps Certification by DevOpsSchool

Explore our DevOps Certification, SRE Certification, and DevSecOps Certification programs at DevOpsSchool. Gain the expertise needed to excel in your career with hands-on training and globally recognized certifications.

0
Would love your thoughts, please comment.x
()
x