Bird
Raised Fist0
Bash Scriptingscripting~10 mins

Looping over files and directories in Bash Scripting - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Looping over files and directories
Start
↓
Get list of files/directories
↓
For each item in list
↓
Process item
↓
More items?
Yes→Process next item
No↓
End
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
Iterationitem valueActionOutput
1file1.txtecho "$item"file1.txt
2file2.txtecho "$item"file2.txt
3dir1echo "$item"dir1
4script.shecho "$item"script.sh
5image.pngecho "$item"image.png
6No more itemsLoop ends
💡 All files and directories matched by * have been processed, loop ends.
Variable Tracker
VariableStartAfter 1After 2After 3After 4After 5Final
itemunsetfile1.txtfile2.txtdir1script.shimage.pngimage.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.

Practice

(1/5)
1. What does the following bash loop do?
for file in *; do echo "$file"; done
easy
A. It runs the echo command once without any output.
B. It deletes all files in the current folder.
C. It lists only directories in the current folder.
D. It prints the names of all files and directories in the current folder.

Solution

  1. Step 1: Understand the loop variable and pattern

    The loop uses * which matches all files and directories in the current folder.
  2. Step 2: Analyze the command inside the loop

    Each matched item is stored in file and printed with echo.
  3. Final Answer:

    It prints the names of all files and directories in the current folder. -> Option D
  4. Quick Check:

    Loop over * prints all names [OK]
Hint: Remember * matches all files and folders [OK]
Common Mistakes:
  • Thinking * matches only files, not directories
  • Assuming the loop deletes files
  • Believing echo runs only once
2. Which of the following is the correct syntax to loop over all directories only in the current folder?
easy
A. for dir in *; do if [ -f "$dir" ]; then echo "$dir"; fi; done
B. for dir in *; do echo "$dir"; done
C. for dir in */; do echo "$dir"; done
D. for dir in /*; do echo "$dir"; done

Solution

  1. Step 1: Understand the pattern for directories

    The pattern */ matches only directories in the current folder because directories end with a slash.
  2. Step 2: Check the loop and echo command

    The loop iterates over directories and prints their names correctly.
  3. Final Answer:

    for dir in */; do echo "$dir"; done -> Option C
  4. Quick Check:

    */ matches directories only [OK]
Hint: Use */ pattern to match directories only [OK]
Common Mistakes:
  • Using * matches files and directories, not only directories
  • Using -f to check for directories instead of -d
  • Using absolute path /* instead of current folder
3. What will be the output of this script if the current folder contains files: file1.txt, file2.txt and a directory docs/?
for item in *; do
  if [ -f "$item" ]; then
    echo "File: $item"
  else
    echo "Not a file: $item"
  fi
done
medium
A. File: file1.txt File: file2.txt Not a file: docs
B. File: file1.txt File: file2.txt File: docs
C. Not a file: file1.txt Not a file: file2.txt Not a file: docs
D. File: file1.txt Not a file: file2.txt Not a file: docs

Solution

  1. Step 1: Identify file and directory checks

    The script uses [ -f "$item" ] to check if the item is a file.
  2. Step 2: Apply checks to each item

    file1.txt and file2.txt are files, so print "File: ..."; docs is a directory, so print "Not a file: docs".
  3. Final Answer:

    File: file1.txt File: file2.txt Not a file: docs -> Option A
  4. Quick Check:

    -f true for files only [OK]
Hint: Use -f to test files, else it's not a file [OK]
Common Mistakes:
  • Assuming directories pass -f test
  • Confusing -f with -d
  • Expecting directory names with trailing slash
4. Find the error in this script that tries to print only directories:
for item in *; do
  if [ -f "$item" ]; then
    echo "$item"
  fi
done
medium
A. The echo command is missing quotes around $item.
B. It uses -f to check files instead of -d for directories.
C. The loop pattern * does not match any files.
D. The script will print directories correctly.

Solution

  1. Step 1: Understand the test used

    The script uses [ -f "$item" ] which checks if the item is a file, not a directory.
  2. Step 2: Identify correct test for directories

    To check directories, [ -d "$item" ] should be used instead.
  3. Final Answer:

    It uses -f to check files instead of -d for directories. -> Option B
  4. Quick Check:

    Use -d to test directories [OK]
Hint: Use -d to check directories, not -f [OK]
Common Mistakes:
  • Confusing -f and -d tests
  • Assuming * matches only directories
  • Ignoring quotes around variables
5. You want to count how many files (not directories) are in the current folder using a bash loop. Which script correctly does this?
hard
A. count=0 for item in *; do if [ -f "$item" ]; then count=$((count + 1)) fi done echo $count
B. count=0 for item in */; do count=$((count + 1)) done echo $count
C. count=0 for item in *; do if [ -d "$item" ]; then count=$((count + 1)) fi done echo $count
D. count=0 for item in *; do count=$((count + 1)) done echo $count

Solution

  1. Step 1: Understand the goal

    We want to count files only, so we must check each item with [ -f "$item" ].
  2. Step 2: Check each option

    count=0 for item in *; do if [ -f "$item" ]; then count=$((count + 1)) fi done echo $count correctly loops over all items, increments count only if item is a file, then prints count.
  3. Final Answer:

    count=0 for item in *; do if [ -f "$item" ]; then count=$((count + 1)) fi done echo $count -> Option A
  4. Quick Check:

    Use -f test and increment count [OK]
Hint: Increment count only if -f test passes [OK]
Common Mistakes:
  • Counting directories instead of files
  • Counting all items without checks
  • Using */ pattern which matches directories only
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard