Start n at 1.
Print and increment n while it is at most 3.
Which loop header is appropriate?
while CONDITION; do ...; done repeats while CONDITION returns status 0. test's -le operator performs the numeric comparison.
Detailed explanation
for [ "$n" -le 3 ]; doIncorrect. for does not take a test command in this form.
Incorrect. for does not take a test command in this form.
while [ "$n" -le 3 ]; doCorrect. The test succeeds while n is less than or equal to 3.
Correct. The test succeeds while n is less than or equal to 3.
case [ "$n" -le 3 ]; doIncorrect. case performs pattern matching, not numeric iteration.
Incorrect. case performs pattern matching, not numeric iteration.
if [ "$n" -le 3 ]; doIncorrect. if uses then and fi and does not repeat.
Incorrect. if uses then and fi and does not repeat.
Try it yourself
An example you can run in a temporary verification environment.
sh -c 'n=1; while [ "$n" -le 3 ]; do printf "%s\n" "$n"; n=$((n + 1)); done'Expected result
1、2、3を1行ずつ表示Key points
- while repeats a condition
- Continue while test succeeds
- Update the counter
Notes
- Environment: POSIX sh / 状態変更なし
- Command output formatting can vary slightly by distribution or tool version.
- Run the example in a temporary directory or process when possible.
Foundation review
Read the scope first
Check whether the command acts on the current shell, a new process, an existing process, or a file.
Verify the observable result
Use the supplied command and compare the output with the expected result.