Logo

Bash Scripting Guide - Control Structures

This section covers control structures in Bash scripting, including conditional statements and loops. Control structures enable you to make decisions and repeat actions based on conditions.

Table of Contents

  1. Conditional Statements
    1. if Statements
    2. elif Statements
    3. Comparison Operators
  2. Loops
    1. for Loop
    2. while Loop
    3. until Loop

1. Conditional Statements

Conditional statements allow you to execute different blocks of code based on specified conditions.

1.1 if Statements

The if statement is used for basic conditional branching.


if [ condition ]; then
    # Code to execute if condition is true
fi

1.2 elif Statements

The elif statement is used for additional conditions in the same block.


if [ condition1 ]; then
    # Code to execute if condition1 is true
elif [ condition2 ]; then
    # Code to execute if condition2 is true
else
    # Code to execute if none of the conditions are true
fi

1.3 Comparison Operators

Use various comparison operators in conditional statements:

Example:


if [ $num -gt 10 ]; then
    echo "Number is greater than 10"
fi

2. Loops

Loops enable you to repeatedly execute a block of code.

2.1 for Loop

The for loop iterates over a sequence.


for variable in sequence; do
    # Code to execute for each iteration
done

Example:


for i in {1..5}; do
    echo "Iteration $i"
done

2.2 while Loop

The while loop executes code as long as a condition is true.


while [ condition ]; do
    # Code to execute while the condition is true
done

Example:


count=0
while [ $count -lt 5 ]; do
    echo "Count: $count"
    ((count++))
done

2.3 until Loop

The until loop executes code until a condition becomes true.


until [ condition ]; do
    # Code to execute until the condition becomes true
done

Example:


num=0
until [ $num -eq 5 ]; do
    echo "Number is $num"
    ((num++))
done


Continue to Part 5: Functions.

Go back to Bash Scripting Guide.

Visit other Developer Guides.