KandZ – Tuts

We like to help…!

Linux CLI 62 🐧 loops in shell scripts

a - while loop in shell scripts
while loop executes its block of commands as long as the given condition remains true
syntax

while [ condition ]; do
Commands to execute
done

[ condition ] is evaluated before each iteration. If the condition evaluates to true, the commands inside the loop are executed.
Once the commands finish executing, the condition is re-evaluated. This process continues until the condition becomes false.
while [ $count -le 5 ] → The loop continues to execute as long as the condition $count is less than or equal to 5 evaluates to true.
you can use the break command to exit the loop prematurely if a certain condition is met.
continue command can be used to skip the rest of the current iteration and move directly to the next iteration.

b - until loop in shell scripts
until loop is a control flow statement that repeatedly executes a block of code as long as a specified condition evaluates to false.
Once the condition becomes true, the loop terminates.
syntax

until [condition]; do
Commands to execute
done

[condition]: The condition that must become true for the loop to exit.
until [ "$user_input" == "exit" ]; do → loop will continue executing as long as the condition is false
while vs until loop
Condition Evaluation:
while: Executes as long as the condition is true.
until: Executes until the condition becomes true.
Typical Use Cases:
while: When you know in advance how many times to loop (e.g., iterating over a range).
until: When you want to keep looping until a specific condition is met (e.g., waiting for an event).

Leave a Reply