Movatterモバイル変換


[0]ホーム

URL:


Menu
×
See More 
Sign In
+1 Get Certified Upgrade Teachers Spaces Bootcamps Get Certified Upgrade Teachers Spaces Bootcamps
   ❮   
     ❯   

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.

Thefor keyword is followed by a variable name, a range of values, and ado keyword, which marks the start of the loop block.

Example: For Loop

# For loop examplefor 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 withdone.

Example: While Loop

# While loop examplecount=1while [ $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 withdone.

Example: Until Loop

# Until loop examplecount=1until [ $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, whilecontinue 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 examplefor i in {1..5}; do  if [ $i -eq 3 ]; then    continue  fi  echo "Number $i"  if [ $i -eq 4 ]; then    break  fidone

Nested Loops

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

Each loop must be closed with its owndone.

Example: Nested Loops

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



×

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

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 ourterms of use,cookies andprivacy policy.

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


[8]ページ先頭

©2009-2026 Movatter.jp