Typorithm · medium

for & while Loops

bash-loopsbashforwhileread
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn for & while Loops

0%

Scripting

for iterates a list or glob, running its body (between do and done) once per item; while read line walks a file line by line when you feed it with done < input.txt. Quote "$f" so filenames with spaces survive.

A for loop iterates a list of words, most often a glob like *.txt that the shell expands into matching filenames. Each value binds to the loop variable, and the body between do and done runs once per item.

Always quote the variable: echo "$f" handles filenames with spaces, where an unquoted $f would split into separate words.

while read line reads the input one line at a time, looping until there is nothing left. Redirecting a file in with done < input.txt feeds that file to read, so the loop processes it line by line. Loops are how scripts handle many items.

01

for binds each glob/list item; body sits between do and done.

02

Quote "$f" to survive spaces in filenames.

03

while read line + done < file walks a file line by line.

for f in *.txt; do
  echo "$f"
done

while read line; do
  echo "$line"
done < input.txt

Read the implementation

Connect each part of the code to the concept before you type.

1. for over a glob

for iterates a list or glob; *.txt expands to every matching filename and binds each to f.

for f in *.txt; do

2. Loop body

The body runs once per item; quoting "$f" keeps filenames with spaces intact.

echo "$f"

3. End of loop

The body lives between do and done, which marks where the loop ends.

done

4. while read

while read line reads one line per iteration until input is exhausted.

while read line; do

5. Feed a file

Redirecting < input.txt into done feeds the file to read, so the loop walks it line by line.

done < input.txt

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

for & while Loops: Lesson & Practice · Typorithm | ApplyDjinn