← Back to Bash Course | Chapter 7: String Manipulation | Lesson 7 of 10

for Loop

In this page:

  1. for Loop

for Loop

A for loop in Bash iterates over a list of words, a range with {1..5}, or a C-style numeric range with ((i=0; i<n; i++)). The classic form, for item in list; do ... done, is the most common style. Bash's for is more flexible than the pure counting loop found in many other languages.

Note: for i in {1..10} is a concise way to iterate over a fixed numeric range without a C-style loop.

Example: for Loop

bash
#!/bin/bash
for i in {1..5}; do
    echo "Number: $i"
done

for ((i = 0; i < 3; i++)); do
    echo "C-style: $i"
done

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.