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.
Conditional statements allow you to execute different blocks of code based on specified conditions.
if
Statements The if
statement is used for basic conditional branching.
if [ condition ]; then
# Code to execute if condition is true
fi
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
Use various comparison operators in conditional statements:
-eq
: Equal -ne
: Not equal -lt
: Less than -le
: Less than or equal -gt
: Greater than -ge
: Greater than or equal Example:
if [ $num -gt 10 ]; then
echo "Number is greater than 10"
fi
Loops enable you to repeatedly execute a block of code.
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
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
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.