010-160 · Question #90
Which of the following examples shows the general structure of a for loop in a shell script?
The correct answer is C. for file in *.txt do echo $i done. The correct Bash for loop uses for variable in list, followed by do, the loop body, and done. Only option C matches this valid shell syntax.
Question
Options
- Afor * .txt == file => echo $file
- Bfor * .txt ( echo $i )
- Cfor file in *.txt do echo $i done
- Dfor ls *.txt exec {} ;
- Eforeach @(file) { echo $i }
How the community answered
(22 responses)- A5% (1)
- C86% (19)
- D9% (2)
Why each option
The correct Bash for loop uses `for variable in list`, followed by `do`, the loop body, and `done`. Only option C matches this valid shell syntax.
The `=>` arrow and `==` syntax are not valid Bash for loop constructs.
Parentheses are not used to delimit Bash for loop bodies; `do` and `done` are required.
Option C uses the correct Bash for loop structure: `for <variable> in <list>`, then `do` on the next line, followed by the command body, and closed with `done`. Although the body references `$i` rather than `$file` (a bug in the question), it is the only syntactically valid shell construct among the choices.
This resembles `find -exec` syntax, not a for loop.
The `foreach` keyword with `@()` and `{{}}` braces is not valid Bash syntax.
Concept tested: Bash shell for loop syntax and structure
Source: https://www.gnu.org/software/bash/manual/bash.html#Looping-Constructs
Topics
Community Discussion
No community discussion yet for this question.