Bird
0
0

Why might using for file in $(ls) to loop over files be problematic?

hard🧠 Conceptual Q10 of 15
Bash Scripting - Loops
Why might using for file in $(ls) to loop over files be problematic?
AIt breaks if filenames contain spaces or newlines
BIt only lists directories, not files
CIt causes an infinite loop
DIt ignores hidden files
Step-by-Step Solution
Solution:
  1. Step 1: Understand command substitution with ls

    Using '$(ls)' splits output on whitespace, so filenames with spaces or newlines break the loop.
  2. Step 2: Identify the problem

    This causes incorrect splitting and unexpected behavior when filenames have spaces or special characters.
  3. Final Answer:

    It breaks if filenames contain spaces or newlines -> Option A
  4. Quick Check:

    Command substitution with ls breaks on spaces = B [OK]
Quick Trick: Avoid 'for file in $(ls)' due to word splitting issues [OK]
Common Mistakes:
MISTAKES
  • Assuming it lists only directories
  • Thinking it causes infinite loops
  • Ignoring hidden files is unrelated here

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Bash Scripting Quizzes