
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"
doneCode language: PHP (php)
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
I’m Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms.
I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.
Find Trusted Cardiac Hospitals
Compare heart hospitals by city and services โ all in one place.
Explore Hospitals