The script starts by getting a list of files and directories, then loops over each item to process it until all items are handled.
Execution Sample
Bash Scripting
for item in *; do
echo "$item"
done
This script loops over all files and directories in the current folder and prints their names one by one.
Execution Table
Iteration
item value
Action
Output
1
file1.txt
echo "$item"
file1.txt
2
file2.txt
echo "$item"
file2.txt
3
dir1
echo "$item"
dir1
4
script.sh
echo "$item"
script.sh
5
image.png
echo "$item"
image.png
6
No more items
Loop ends
💡 All files and directories matched by * have been processed, loop ends.
Variable Tracker
Variable
Start
After 1
After 2
After 3
After 4
After 5
Final
item
unset
file1.txt
file2.txt
dir1
script.sh
image.png
image.png
Key Moments - 3 Insights
Why does the loop stop after the last file is processed?
The loop stops because the glob * expands to all files and directories once. After the last item is processed (row 5 in execution_table), there are no more items to loop over, so the loop ends (row 6).
What happens if there are no files or directories in the folder?
If the folder is empty, the glob * expands to itself as a string '*', so the loop runs once with item='*'. This can be avoided by checking if the item is a real file or directory inside the loop.
Why do we use quotes around "$item" in echo?
Quotes ensure that if the filename has spaces or special characters, it is treated as a single string and printed correctly, avoiding word splitting or errors.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'item' at iteration 3?
Ascript.sh
Bfile2.txt
Cdir1
Dfile1.txt
💡 Hint
Check the 'item value' column at iteration 3 in the execution_table.
At which iteration does the loop end because there are no more items?
A6
B4
C5
D7
💡 Hint
Look for the row in execution_table where the action says 'No more items'.
If the folder is empty, what will the loop variable 'item' be set to during the loop?
Aempty string
Bthe string '*'
Cnull
Dno loop runs
💡 Hint
Refer to the key_moments section about what happens when the folder is empty.
Concept Snapshot
Loop over files/directories using: for item in *; do ... done
The * expands to all files and folders in current directory.
Each item is processed one by one inside the loop.
Use quotes around "$item" to handle spaces.
Loop ends when all items are processed.
Full Transcript
This lesson shows how to loop over files and directories in bash using a for loop with the * wildcard. The * expands to all files and directories in the current folder. The loop variable 'item' takes each filename one by one. Inside the loop, we can run commands on each item, like echo to print its name. The loop stops after all items are processed. If the folder is empty, the loop runs once with item='*'. Using quotes around "$item" ensures filenames with spaces print correctly. This visual trace helps beginners see each step and variable change clearly.