Loop in Shell Script : Repeating tasks is a common need in programming, and Bash scripting makes it super simple with loops. Whether you’re a total beginner or just brushing up, this guide will walk you through for
, while
, and until
loops in Bash in a clear and practical way.
Loop in Shell Script :
Why Loops Matter in Bash
Loops let you automate repetitive tasks, saving time and reducing errors. Imagine printing numbers, processing files, or running commands multiple times — loops make it all easy.
In Bash, there are three main types of loops:
for
loop – great for iterating over a list or rangewhile
loop – runs as long as a condition is trueuntil
loop – runs until a condition becomes true
Let’s explore each with easy examples!
The for
Loop
The for
loop is perfect when you know how many times you want to repeat a task.
Syntax:
for variable in list
do
# commands
done
Example 1: Print numbers 1 to 5
for i in 1 2 3 4 5
do
echo "Number: $i"
done
Example 2: Loop through a list of names
for name in Alice Bob Charlie
do
echo "Hello, $name!"
done
The while
Loop
The while
loop continues as long as a condition is true.
Syntax:
while [ condition ]
do
# commands
done
Example: Count from 1 to 5
count=1
while [ $count -le 5 ]
do
echo "Count: $count"
((count++))
done
Tip: Always make sure your condition will eventually become false to avoid infinite loops!
The until
Loop
The until
loop is like the opposite of while
. It runs until the condition is true.
Syntax:
until [ condition ]
do
# commands
done
Example: Count from 1 to 5 using until
count=1
until [ $count -gt 5 ]
do
echo "Count: $count"
((count++))
done
Notice the key difference: until
continues as long as the condition is false.
Bash Loop Tips for Beginners
- Use
echo
to debug your loop logic. - Prefer
for
loops for simple repetitions and lists. - Use
while
oruntil
for more flexible conditions. - Don’t forget the
do
anddone
keywords!
Is do while
supported in Bash?
No, Bash does not support do...while
loops directly.
In C/C++, a do...while
loop runs at least once, and checks the condition after executing the block.
// In C
do {
// code
} while (condition);
Workaround in Bash
You can simulate a do...while
loop in Bash using a while
loop with a break
condition inside.
Bash Equivalent (Simulating do...while
):
count=1
while true
do
echo "Count: $count"
((count++))
if [ $count -gt 5 ]; then
break
fi
done
Here’s what’s happening:
while true
ensures the loop runs at least once.- We manually check the condition after executing the body.
break
exits the loop once the condition is met — mimickingdo...while
.
Pro Tip
If you must ensure a loop runs at least once in Bash, this pattern is your go-to replacement for do...while
.
FAQ | Learn How to Repeat Tasks Using for
, while
, and until
Loops in Bash
1. What is a loop in Bash?
A loop in Bash is a control structure that allows you to repeat a task or a set of tasks multiple times without needing to write the same code over and over again. Loops are essential for automating repetitive tasks in your Bash scripts.
2. What’s the difference between for
, while
, and until
loops in Bash?
for
loop: Executes a block of code for each item in a list or a range. Ideal when you know how many times you want the loop to run.while
loop: Runs as long as a given condition is true. Use this when the number of iterations isn’t fixed, but the condition should be true.until
loop: Similar towhile
, but it runs until the condition becomes true, meaning it stops when the condition is true.
3. When should I use a for
loop in Bash?
Use a for
loop when you want to iterate over a list or a range of numbers. It’s perfect for scenarios where you know the exact number of iterations you need.
Example:
for i in 1 2 3 4 5
do
echo "Iteration: $i"
done
4. How do while
and until
loops differ?
- A
while
loop checks if a condition is true before executing the code block. It continues as long as the condition remains true. - An
until
loop works oppositely. It checks if a condition is false and will continue executing the block until the condition becomes true.
Example while
:
count=1
while [ $count -le 5 ]
do
echo "Count: $count"
((count++))
done
Example until
:
count=1
until [ $count -gt 5 ]
do
echo "Count: $count"
((count++))
done
5. How can I stop an infinite loop in Bash?
To prevent an infinite loop, make sure your loop condition will eventually become false. However, if you do find yourself in an infinite loop, you can stop it by pressing Ctrl+C
in the terminal.
6. Can I combine multiple loops in Bash?
Yes, you can nest loops in Bash. This means you can place one loop inside another. Here’s an example with a for
loop inside a while
loop:
count=1
while [ $count -le 3 ]
do
for i in 1 2 3
do
echo "Count: $count, Inner loop: $i"
done
((count++))
done
7. What is the syntax for for
, while
, and until
loops?
for
loop:for variable in list do # commands done
while
loop:while [ condition ] do # commands done
until
loop:until [ condition ] do # commands done
8. Can I use a for
loop with ranges in Bash?
Yes, you can. Bash supports range iteration in for
loops by specifying a range like this:
for i in {1..5}
do
echo "Number: $i"
done
This will output numbers from 1 to 5.
9. What happens if I forget the do
or done
in a loop?
If you forget do
or done
, Bash will throw a syntax error. Both do
and done
are essential to mark the start and end of the code block inside loops.
10. Can I break out of a loop in Bash?
Yes! You can use the break
command to exit a loop early, regardless of the loop condition.
Example:
for i in {1..10}
do
if [ $i -eq 5 ]; then
break
fi
echo "Number: $i"
done
This will print numbers 1 to 4, then exit the loop when $i
equals 5.
11. What is the continue
statement used for in loops?
The continue
statement skips the rest of the current iteration and moves to the next iteration of the loop.
Example:
for i in {1..5}
do
if [ $i -eq 3 ]; then
continue
fi
echo "Number: $i"
done
This will skip the number 3 and print 1, 2, 4, 5
You can also Visit other tutorials of Embedded Prep
- What is eMMC (Embedded MultiMediaCard) memory ?
- Top 30+ I2C Interview Questions
- Bit Manipulation Interview Questions
- Structure and Union in c
- Little Endian vs. Big Endian: A Complete Guide
- Merge sort algorithm
Special thanks to @embedded-prep for contributing to this article on Embedded Prep
Mr. Raj Kumar is a highly experienced Technical Content Engineer with 7 years of dedicated expertise in the intricate field of embedded systems. At Embedded Prep, Raj is at the forefront of creating and curating high-quality technical content designed to educate and empower aspiring and seasoned professionals in the embedded domain.
Throughout his career, Raj has honed a unique skill set that bridges the gap between deep technical understanding and effective communication. His work encompasses a wide range of educational materials, including in-depth tutorials, practical guides, course modules, and insightful articles focused on embedded hardware and software solutions. He possesses a strong grasp of embedded architectures, microcontrollers, real-time operating systems (RTOS), firmware development, and various communication protocols relevant to the embedded industry.
Raj is adept at collaborating closely with subject matter experts, engineers, and instructional designers to ensure the accuracy, completeness, and pedagogical effectiveness of the content. His meticulous attention to detail and commitment to clarity are instrumental in transforming complex embedded concepts into easily digestible and engaging learning experiences. At Embedded Prep, he plays a crucial role in building a robust knowledge base that helps learners master the complexities of embedded technologies.
Leave a Reply