Which of the following is syntactically valid in a standard Bash shell script…
2024
Which of the following is syntactically valid in a standard Bash shell script for iterating through a list of values using a for loop?
- A.
for(i=0; i<5; i++)
{
} - B.
for i in 1 2 3 4 5
do
echo $i
done - C.
foreach i = 1 to 5
echo $i
end - D.
loop i from 1 to 5
print $i - E.
for i = 1:5
echo $i
endfor
Attempted by 5 students.
Show answer & explanation
Correct answer: B
Concept
In the Bourne-again shell (Bash), the list form of the for loop has a fixed keyword skeleton: the loop variable is named after for, the values it walks over follow the in keyword, and the body that runs once per value is bracketed by the do and done keywords. The general shape is:
for VAR in WORD1 WORD2 ... ; do
COMMANDS
doneThe do ... done pair is mandatory; Bash does not use C-style curly braces { } to delimit a loop body, and it has no foreach, loop, or endfor keywords.
Applying it here
Read each candidate and test it against that skeleton, keyword by keyword:
for i in 1 2 3 4 5 do echo $i done— names the variable i, lists the five values after in, opens the body with do, runs echo $i once per value, and closes with done. Every required keyword is present and in order, so this is valid Bash (the line breaks shown stand in for the statement separators).for(i=0; i<5; i++) { }— this is the C / Java arithmetic-for shape with curly-brace delimiters. Bash's own arithmetic form is for ((i=0; i<5; i++)); do ...; done with double parentheses and do/done, never single parens plus { }.foreach i = 1 to 5 echo $i end— foreach ... end is C-shell (csh/tcsh) syntax, not Bash; Bash has no foreach keyword.loop i from 1 to 5 print $i— none ofloop,from, orprintis a Bash loop keyword, so this is not a for-loop construct at all. Bash would instead read the line as a plain command namedloop, which fails at run time with "command not found" rather than iterating; it is pseudocode.for i = 1:5 echo $i endfor— the 1:5 range, the = assignment, and endfor are MATLAB-style, not Bash.
Cross-check
Only one candidate uses the for ... in ... do ... done keyword set that Bash actually recognises. Pasting it into a Bash shell prints 1 through 5 on separate lines, confirming it iterates. None of the other four iterates: the C-style for(...) { } header and the MATLAB-style for i = 1:5 ... endfor both break Bash's grammar and raise a syntax error, while the foreach and loop lines are parsed as unknown command names and fail at run time with "command not found".