LPIC-1 Shells, Scripting and Data Management Practice Question
Which shell loop is most appropriate for iterating over all files in a directory, performing an action only on regular files, while safely handling filenames with spaces?
⚠ Common exam trap
Watch out — candidates often assume ls output is safe for iteration, but the shell's word splitting and globbing on unquoted command substitutions cause failures with spaces, making the glob pattern the only reliable method.
Answer choices
Why each option matters
Answer the question above first, then reveal the full breakdown to understand why each option is right or wrong.
Correct answer & explanation
✓
for file in *; do if [ -f "$file" ]; then ... ; done
It uses a glob pattern (*) to iterate over all files in the current directory, which is safe for filenames with spaces. The double quotes around "$file" in the test condition [ -f "$file" ] ensure that filenames containing spaces or special characters are handled as a single argument, preventing word splitting. This approach avoids parsing the output of ls, which is unreliable and can break with unusual filenames.
Answer analysis
Option-by-option breakdown
For each option: why learners choose it and why it is or isn't the right answer here.
- ✗
for file in "`ls`"; do ...
Why it's wrong here
Treats all filenames as one string.
- ✗
for file in `ls`; do if [ -f $file ]; then ... ; done
Why it's wrong here
Word splitting on spaces; unquoted.
- ✗
for file in $(ls); do if [ -f "$file" ]; then ... ; done
Why it's wrong here
Word splitting on spaces.
- ✓
for file in *; do if [ -f "$file" ]; then ... ; done
Why this is correct
Correctly handles spaces and regular files.
Go deeper
Related to this question
About these practice questions
Courseiva writes every LPIC-1 question from scratch — 527 in total, each with an explanation and a wrong-answer breakdown. None are copied from real exams or dumps. Learn why practice questions differ from exam dumps →
JA
Written by Johnson Ajibi, MSc IT Security
Senior Network & Security Engineer · founder of Courseiva
This LPIC-1 practice question is part of Courseiva's free LPI certification practice question bank. Courseiva provides original exam-style practice questions with explanations, topic-based practice, mock exams, readiness tracking, and study analytics to help learners prepare for the LPIC-1 exam.