[フレーム]

Bash Loops


Using Loops in Bash

This section covers the use of loops in Bash scripting, including for, while, and until loops.


For Loops

For loops allow you to iterate over a list of items or a range of numbers. They are useful for repeating tasks a specific number of times.

The for keyword is followed by a variable name, a range of values, and a do keyword, which marks the start of the loop block.

Example: For Loop

# For loop example
for i in {1..5}; do
 echo "Iteration $i"
done

While Loops

While loops execute a block of code as long as a specified condition is true.

They are useful for tasks that need to repeat until a certain condition changes.

The condition is enclosed in square brackets [ ], and the loop ends with done.

Example: While Loop

# While loop example
count=1
while [ $count -le 5 ]; do
 echo "Count is $count"
 ((count++))
done


Until Loops

Until loops are similar to while loops, but they execute until a specified condition becomes true.

The condition is enclosed in square brackets [ ], and the loop ends with done.

Example: Until Loop

# Until loop example
count=1
until [ $count -gt 5 ]; do
 echo "Count is $count"
 ((count++))
done

Break and Continue

Break and continue statements are used to control loop execution. break exits the loop, while continue skips to the next iteration.

These statements are typically used inside conditional blocks to alter the flow of the loop.

Example: Break and Continue

# Break and continue example
for i in {1..5}; do
 if [ $i -eq 3 ]; then
 continue
 fi
 echo "Number $i"
 if [ $i -eq 4 ]; then
 break
 fi
done

Nested Loops

Nested loops allow you to place one loop inside another, enabling more complex iteration patterns.

Each loop must be closed with its own done.

Example: Nested Loops

# Nested loops example
for i in {1..3}; do
 for j in {1..2}; do
 echo "Outer loop $i, Inner loop $j"
 done
done


New

W3Schools Adventure App

Coding fundamentals as a game. Bite-sized lessons and challenges.

Ready to start your journey? Your streak is waiting.
+60 XP
W3Schools Adventure tutor
W3Schools Adventure map
×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

FORUM ABOUT ACADEMY
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness
of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.

AltStyle によって変換されたページ (->オリジナル) /