Which three loop headers cause a bash script to iterate exactly over the numbers 1 to 5? Assume default bash options and an empty current directory. (Choose three.)
LPIC-1 Exam 102-500, objective 105. Shells and shell scripting medium
Draft — not checked yet. This question was written from the published exam objectives and cites the clause it comes from, but nobody has yet read it against that clause and signed for it.
It is kept out of search results and out of mock exams until they have. Read the source below before you take the answer as settled.
The options
Choose 3.
Not correct for i in 1 to 5; do
Wrong. There is no `to` keyword in bash. This loops three times, over the literal words 1, to and 5.
Correct for i in {1..5}; do
Correct. Brace expansion produces the words 1 2 3 4 5. Note that it happens before variable expansion, so {1..$n} does not work.
Correct for i in $(seq 1 5); do
Correct. Command substitution runs seq, which prints 1 to 5 one per line, and the shell splits that output into words. Unlike brace expansion this accepts variables.
Correct for (( i=1; i<=5; i++ )); do
Correct. This is bash's arithmetic for loop, using the same three-part form as C. It is a bash extension, not POSIX sh.
Not correct for i in [1-5]; do
Wrong. Square brackets form a filename glob matching one character in the range. If no file in the current directory is named 1 through 5, the pattern stays unmatched and the loop runs once with i set to the literal string [1-5].
Why
A `for NAME in WORDS` loop iterates over a word list, so the interesting part is how you generate the list: brace expansion {1..5} for literal ranges, $(seq FIRST LAST) when the bounds come from variables, or the arithmetic (( )) form when you want C-style control. Brace expansion is the fastest since no external process runs.
Where this comes from
- Cited
- LPI exam objective 105.2
- What it says
- Use loops and command substitution in shell scripts.
Practise this
Reading one question is not practice. The trainer will draw a set from objective 105 and space the ones you get wrong.