Control structures allow a script to make decisions and execute code conditionally or repeatedly. There are three main types:
-
Conditional Statements (
if
,case
) -
Loops (
for
,while
,until
) -
Branching (
break
,continue
)
1. Conditional Statements
a) If-Else Statement
Used for decision-making based on conditions.
Syntax:
Example:
📌 Common Comparison Operators:
Operator | Description |
---|---|
-eq |
Equal to |
-ne |
Not equal to |
-gt |
Greater than |
-lt |
Less than |
-ge |
Greater than or equal to |
-le |
Less than or equal to |
b) Case Statement
Used when multiple conditions need to be checked, similar to switch
in other languages.
Syntax:
Example:
2. Loops
Loops are used to execute a block of code multiple times.
a) For Loop
Repeats execution a set number of times.
Syntax:
Example:
Using a Range:
Using C-style Syntax:
b) While Loop
Executes while a condition is true.
Syntax:
Example:
c) Until Loop
Similar to while
, but runs until the condition becomes true.
Syntax:
Example:
3. Loop Control Statements
a) Break Statement
Exits a loop immediately.
b) Continue Statement
Skips the rest of the loop’s body and moves to the next iteration.
🚀 Putting It All Together: A Complete Example
🔥 Key Takeaways
✅ If-Else: Used for decision-making.
✅ Case Statement: Simplifies multiple conditions.
✅ Loops: for
, while
, and until
automate repetitive tasks.
✅ Break & Continue: Control loop execution flow.
1️⃣ If-Else Statements (More examples, nested conditions)
2️⃣ Case Statements (Pattern matching, advanced use cases)
3️⃣ For Loop (Iterating over arrays, files, numbers)
4️⃣ While/Until Loops (Real-world automation examples)
5️⃣ Break & Continue (Use in nested loops)
6️⃣ A Complete Script Combining All Concepts