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

for Loop

A for loop is like a chore chart where you do the same task once for each name on the list. It is the easy way to repeat something for every item or every number in a range.

In this page:

  1. for Loop
Syntax
bash
for variable in list; do
  commands
done

for variable in {1..5}; do
  commands
done

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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Writing for i in {1..$n}, since brace expansion does not expand variables; use seq or a C-style loop.
  2. Looping over $(ls) with names containing spaces, when for f in * is safer.
  3. Forgetting do or done, which gives a syntax error.

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.