|
The The condition is tested BEFORE each iteration. If false initially, the loop body never runs at all. |
|
|
Output:
Count: 1 Count: 2 Count: 3 Count: 4 Count: 5 |
|
|
While loops shine when you don’t know in advance how many
iterations you need. Unlike Use
|
|
|
Output:
For loop (fixed list): a b c While loop (condition-based): iteration 1 iteration 2 iteration 3 |
|
|
Counting is a common use of |
|
|
Output:
Counting up: 1 2 3 Counting down: 3 2 1 Liftoff! |
|
|
The These two forms are equivalent:
|
|
|
Output:
Using while (with negated condition): num is 1 num is 2 num is 3 Using until (same result): num is 1 num is 2 num is 3 |
|
|
You can combine multiple conditions using
|
|
|
Output:
Using && (both must be true): x=0, y=10 x=1, y=9 x=2, y=8 Using || (either can be true): a=0, b=0 a=1, b=1 a=2, b=2 |
|
|
As with |
|
|
Output:
Break example (exit on condition): Iteration 1 Iteration 2 Iteration 3 Breaking out Continue example (skip even numbers): Odd: 1 Odd: 3 Odd: 5 |
|
|
Processing command output line by line is a common pattern.
Pipe the command into a Important: Variables modified inside a piped |
|
|
Output:
Processing lines from a command: Got: first Got: second Got: third Count after piped loop: 0 (still 0 due to subshell) |
|
|
The Each |
|
|
Output:
Processing 4 arguments: Current arg: apple (remaining: 4) Current arg: banana (remaining: 3) Current arg: cherry (remaining: 2) Current arg: date (remaining: 1) Done. Arguments remaining: 0 |
|
|
Retry logic is a common pattern for operations that may fail temporarily, like network requests or file locks. The loop attempts the operation up to a maximum number of times, exiting early on success. In real scripts, you would typically add |
|
|
Output:
Attempt 1 of 3 Failed, will retry... Attempt 2 of 3 Failed, will retry... Attempt 3 of 3 Success! Operation completed successfully |
|
|
Reading lines safely requires two techniques:
The Note: This example uses a here-document ( |
|
|
Output:
Line: ' indented line' Line: 'line with trailing space' Line: 'normal line' |
|