Control Structures
Control structures allow your script to make decisions and repeat tasks.
1. Conditionals: if-else
In Bash, we use [ or [[ to perform tests.
#!/bin/bash
read -p "Enter your age: " AGE
if [ "$AGE" -ge 18 ]; then
echo "You are an adult."
elif [ "$AGE" -gt 12 ]; then
echo "You are a teenager."
else
echo "You are a child."
fiCommon Operators
-eq: Equal to.-ne: Not equal to.-gt: Greater than.-lt: Less than.-z: String is empty.-f: File exists and is a regular file.
2. Loops
for Loop
Used to iterate over a list of items.
#!/bin/bash
# Loop through a range
for i in {1..5}; do
echo "Iteration $i"
done
# Loop through files
for FILE in *.txt; do
echo "Processing $FILE..."
donewhile Loop
Repeats as long as a condition is true.
#!/bin/bash
COUNT=1
while [ $COUNT -le 3 ]; do
echo "Waiting for service... attempt $COUNT"
((COUNT++))
sleep 1
doneSummary Matrix
| Structure | Use Case |
|---|---|
if | Branching logic based on a condition. |
for | Iterating over a known list of items. |
while | Repeating until a condition is met. |
[!TIP] Use Double Brackets Whenever possible, use
[[ ... ]]instead of[ ... ]. It is more powerful and handles things like empty variables or regex much better.