nerdexam
LPI

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.

The Power of the Command Line

Question

Which of the following examples shows the general structure of a for loop in a shell script?

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)
  • A
    5% (1)
  • C
    86% (19)
  • D
    9% (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.

Afor * .txt == file => echo $file

The `=>` arrow and `==` syntax are not valid Bash for loop constructs.

Bfor * .txt ( echo $i )

Parentheses are not used to delimit Bash for loop bodies; `do` and `done` are required.

Cfor file in *.txt do echo $i doneCorrect

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.

Dfor ls *.txt exec {} \;

This resembles `find -exec` syntax, not a for loop.

Eforeach @(file) { echo $i }

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

#for loop#shell scripting#bash syntax#control flow

Community Discussion

No community discussion yet for this question.

Full 010-160 Practice