ACE-P-ALE1-04 practice question 13 of 35

Which loop type is the recommended way to iterate over a set of filenames?

Full set: 100 questions
Answer options
A: a case loop
B: a for loop Correct answer
C: a while loop
D: an until loop
Correct Answer:
B. a for loop
Explanation

The for loop is the standard and most idiomatic construct in shell scripting for iterating over a static list of items, such as a set of filenames. Its syntax (for variable in list...) is designed specifically for this purpose, making the code clear and concise. It directly processes each item in the provided list until the list is exhausted. While other loops can be adapted for this task, the for loop is the most direct and recommended method.

Why Incorrect

A. A case statement is a conditional construct used for pattern matching against a single variable; it is not a loop and does not perform iteration.
C. A while loop is condition-based, executing as long as a condition is true. It is better suited for tasks where the number of iterations is unknown beforehand.
D. An until loop is also condition-based, executing as long as a condition is false. It is not designed for iterating over a predefined list of items.

References

1. GNU Bash Reference Manual, Section 3.2.5.1 Looping Constructs (for): "The for loop executes a sequence of commands for each member in a list of items... This is the most commonly used looping construct in shell scripts." This section explicitly describes the for loop's primary purpose as iterating over a list.

2. MIT OpenCourseWare, "The Missing Semester of Your CS Education", Lecture 2: Shell Tools and Scripting: The lecture materials demonstrate the use of for loops specifically for iterating over files (e.g., for file in ./). It contrasts this with while loops, which are shown for reading input line-by-line, highlighting the distinct use cases.

3. Arista EOS Central, "Using Bash in EOS": While not a tutorial, examples within Arista's technical articles and community forums consistently use for loops when scripting actions across a known set of interfaces, files, or other list-based elements within the EOS environment, reinforcing its standard usage. For example, a script might use for vlan in $(cat vlan.list) to iterate through a list of VLANs from a file.

Scroll to Top