CodeToLive

Bash Control Flow

Control flow statements allow you to make decisions and repeat actions in your Bash scripts. Mastering these constructs is essential for writing powerful and flexible scripts.

Conditional Statements

if-then-else


if [ condition ]; then
    # commands
elif [ another_condition ]; then
    # commands
else
    # commands
fi
                

Test Conditions

The [ ] construct (or [[ ]] in Bash) is used to evaluate conditions:

Condition Description
-f file File exists and is regular
-d file File exists and is directory
-e file File exists
-z string String is empty
-n string String is not empty
str1 = str2 Strings are equal
str1 != str2 Strings are not equal
int1 -eq int2 Integers are equal
int1 -ne int2 Integers are not equal
int1 -gt int2 int1 > int2
int1 -lt int2 int1 < int2

Example: File Check


if [ -f "/path/to/file" ]; then
    echo "File exists"
else
    echo "File does not exist"
fi
                

Case Statements

Alternative to multiple if-elif statements:


case $variable in
    pattern1)
        # commands
        ;;
    pattern2)
        # commands
        ;;
    *)
        # default commands
        ;;
esac
                

Example: Menu System


echo "Select option:"
echo "1) Option 1"
echo "2) Option 2"
echo "3) Quit"

read -p "Enter choice: " choice

case $choice in
    1) echo "You chose Option 1" ;;
    2) echo "You chose Option 2" ;;
    3) echo "Goodbye!"; exit ;;
    *) echo "Invalid option" ;;
esac
                

Loops

for Loop


# Iterate over list
for item in list; do
    # commands
done

# C-style for loop
for (( i=0; i<10; i++ )); do
    echo $i
done
                

while Loop


while [ condition ]; do
    # commands
done
                

until Loop


until [ condition ]; do
    # commands
done
                

Loop Control


for i in {1..5}; do
    if [ $i -eq 3 ]; then
        continue  # Skip this iteration
    fi
    echo $i
    if [ $i -eq 4 ]; then
        break  # Exit loop
    fi
done
                

Flow Diagram Examples

if-then-else Flow

START
Is condition true?
Execute 'then' block
Is elif condition true?
Execute 'elif' block
Execute 'else' block
END

for Loop Flow

START
Initialize loop
More items?
Process current item
Increment/next item
END

Practical Examples

File Processing


# Process all .txt files in directory
for file in *.txt; do
    echo "Processing $file"
    # Add your processing commands here
done
                

User Input Validation


while true; do
    read -p "Enter yes or no: " answer
    case $answer in
        [Yy]*) echo "You said yes"; break ;;
        [Nn]*) echo "You said no"; break ;;
        *) echo "Invalid answer" ;;
    esac
done
                

Countdown Timer


count=5
while [ $count -gt 0 ]; do
    echo $count
    sleep 1
    ((count--))
done
echo "Blast off!"
                

Best Practices

  • Use [[ ]] instead of [ ] for more features and safety
  • Quote variables in test conditions to prevent errors
  • Use meaningful variable names in loops
  • Indent nested control structures for readability
  • Add comments explaining complex conditions

Next Steps

Continue learning with: