Deal of The Day! Hurry Up, Grab the Special Discount - Save 25% - Ends In 00:00:00 Coupon code: SAVE25
Welcome to Pass4Success

- Free Preparation Discussions

LPI 010-160 Exam - Topic 5 Question 71 Discussion

Which of the following examples shows the general structure of a for loop in a shell script?
C) for file in *.txt do echo $i done
A) for *.txt as file => echo $file
B) for *.txt ( echo $i )
D) for ls *.txt exec {} \;
E) foreach @{file} { echo $i }

LPI 010-160 Exam - Topic 5 Question 71 Discussion

Actual exam question for LPI's 010-160 exam
Question #: 71
Topic #: 5
[All 010-160 Questions]

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

Show Suggested Answer Hide Answer
Suggested Answer: C

The general structure of a for loop in a shell script is as follows12:

for variable in list do commands done

The variable is the name of a loop counter or iterator that takes on the values of the items in the list. The list can be a sequence of words, numbers, filenames, or the output of a command. The commands are the body of the loop that are executed for each value of the variable. The do and done keywords mark the beginning and the end of the loop body.

The option C. for file in *.txt do echo $i done follows this structure, with the variable being file, the list being *.txt (which matches all the files with the .txt extension in the current directory), and the command being echo $i (which prints the value of the variable i, which is presumably set somewhere else in the script).

The other options are incorrect because:

A . for *.txt as file => echo $file uses an invalid syntax for a for loop. The as keyword is not part of the shell script syntax, and the => symbol is not a valid operator. The correct way to write this loop would be:

for file in *.txt do echo $file done

B . for *.txt ( echo $i ) uses an invalid syntax for a for loop. The parentheses are not part of the shell script syntax, and the loop body is missing the do and done keywords. The correct way to write this loop would be:

for i in *.txt do echo $i done

D . for ls *.txt exec {} ; uses an invalid syntax for a for loop. The ls command is not a valid variable name, and the exec {} ; is not a valid command. This looks like a mix of a for loop and a find command. The correct way to write this loop would be:

for file in *.txt do exec $file done

E . foreach @{file} { echo $i } uses an invalid syntax for a for loop. The foreach keyword is not part of the shell script syntax, and the @{file} and { echo $i } are not valid expressions. This looks like a mix of a for loop and a Perl syntax. The correct way to write this loop would be:

for file in * do echo $file done


Looping Statements | Shell Script - GeeksforGeeks

How do I write a 'for' loop in Bash? - Stack Overflow

Contribute your Thoughts:

0/2000 characters

Currently there are no comments in this discussion, be the first to comment!


Save Cancel