0
0
Bash-scriptingHow-ToBeginner · 3 min read

How to Use For Loop in Bash: Syntax and Examples

In bash, a for loop repeats commands for each item in a list or range. Use the syntax for variable in list; do commands; done to run commands for each item.
📐

Syntax

The basic syntax of a for loop in bash is:

  • variable: a name that holds the current item in the loop.
  • list: a series of values or a range to loop over.
  • do ... done: the block of commands to run for each item.
bash
for variable in list; do
  commands
 done
💻

Example

This example prints numbers 1 to 5 using a for loop:

bash
for i in 1 2 3 4 5; do
  echo "Number: $i"
done
Output
Number: 1 Number: 2 Number: 3 Number: 4 Number: 5
⚠️

Common Pitfalls

Common mistakes include missing do or done, forgetting spaces, or not quoting variables when needed. Also, using incorrect list syntax can cause errors.

Wrong example (missing do):

bash
for i in 1 2 3 4 5
  echo "$i"
done

# Corrected version:
for i in 1 2 3 4 5; do
  echo "$i"
done
📊

Quick Reference

ElementDescriptionExample
variableHolds current itemi
listItems to loop over1 2 3 4 5 or $(seq 1 5)
do ... doneCommands blockdo echo $i; done

Key Takeaways

Use 'for variable in list; do ... done' to loop over items in bash.
Always include 'do' and 'done' keywords to define the loop block.
Separate list items with spaces or use command substitution for ranges.
Quote variables inside the loop to avoid word splitting issues.
Test loops with simple commands to avoid syntax errors.