200-901 · Question #505
200-901 Question #505: Real Exam Question with Answer & Explanation
The correct answer is D: for file in files;. A Bash for loop that iterates over a pre-defined variable containing filenames uses the variable reference in the 'in' clause so each filename is assigned to the loop variable one at a time.
Question
Refer to the exhibit. An engineer needs to construct a Bash command to create a new backup folder and then copy all files from the current folder to the backup folder. Which code snippet must be placed on the blank in the code? A. B. C. D.
Options
- Afor file in $ (cd);
- Bfor file in $ (ls);
- Cfor files in $ (ls);
- Dfor file in files;
Explanation
A Bash for loop that iterates over a pre-defined variable containing filenames uses the variable reference in the 'in' clause so each filename is assigned to the loop variable one at a time.
Common mistakes.
- A. $(cd) executes the cd command inside command substitution, which produces no output and returns no filenames, so the loop body never executes meaningfully.
- B. $(ls) would produce filenames via command substitution, but this choice is eliminated because the exhibit context requires iterating over a pre-assigned variable rather than re-running ls inline.
- C. Using 'files' as the loop variable name (plural) would conflict with the loop body that references the singular variable 'file', causing the copy command to fail with an unbound variable error.
Concept tested. Bash for loop variable iteration syntax
Reference. https://www.gnu.org/software/bash/manual/bash.html#Looping-Constructs
Topics
Community Discussion
No community discussion yet for this question.