200-901 · Question #505
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…
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;
How the community answered
(26 responses)- A4% (1)
- C4% (1)
- D92% (24)
Why each option
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.
$(cd) executes the cd command inside command substitution, which produces no output and returns no filenames, so the loop body never executes meaningfully.
$(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.
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.
Using 'for file in $files;' (where $files holds the list of filenames) correctly assigns each filename to the singular loop variable 'file' on each iteration, which is then used in the subsequent copy command. The singular name 'file' matches the expected reference in the loop body that performs the cp operation on one file at a time.
Concept tested: Bash for loop variable iteration syntax
Source: https://www.gnu.org/software/bash/manual/bash.html#Looping-Constructs
Topics
Community Discussion
No community discussion yet for this question.