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:
Syntax
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
#!/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 try C/C++/Java/PHP code in the editor
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
- Writing
for i in {1..$n}, since brace expansion does not expand variables; useseqor a C-style loop. - Looping over
$(ls)with names containing spaces, whenfor f in *is safer. - Forgetting
doordone, which gives a syntax error.
🔒
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: