G
GuideDevOps
Lesson 4 of 15

Conditional Statements

Part of the Shell Scripting (Bash) tutorial series.

The if Statement

Basic Syntax

if [ condition ]; then
    # Commands if condition is true
fi

With else and elif

if [ condition1 ]; then
    # If condition1 is true
elif [ condition2 ]; then
    # If condition2 is true
else
    # If neither is true
fi

File Tests

# File exists
if [ -e "/path/to/file" ]; then echo "File exists"; fi
 
# Is regular file
if [ -f "/path/to/file" ]; then echo "Regular file"; fi
 
# Is directory
if [ -d "/path/to/dir" ]; then echo "Directory"; fi
 
# File is readable, writable, executable
if [ -r "$file" ] && [ -w "$file" ] && [ -x "$file" ]; then
    echo "Has all permissions"
fi
 
# File has content (size is greater than zero)
if [ -s "/path/to/file" ]; then echo "File has content"; fi

String and Numeric Comparisons

# String equal/not equal
if [ "$str1" = "$str2" ]; then echo "Equal"; fi
if [ "$str1" != "$str2" ]; then echo "Not equal"; fi
 
# String empty or not
if [ -z "$str" ]; then echo "Empty"; fi
if [ -n "$str" ]; then echo "Not empty"; fi
 
# Numeric comparisons: -eq -ne -lt -gt -le -ge
if [ $num1 -lt $num2 ]; then echo "Less than"; fi
if [ $num1 -ge $num2 ]; then echo "Greater or equal"; fi

Logical Operators

# AND
if [ -f "$file" ] && [ -r "$file" ]; then
    echo "File exists and is readable"
fi
 
# OR
if [ -f "$file" ] || [ -h "$file" ]; then
    echo "Is file or symlink"
fi
 
# NOT
if [ ! -f "$file" ]; then
    echo "Is not a file"
fi

The case Statement

case $var in
    pattern1)
        echo "Matched pattern1"
        ;;
    pattern2|pattern3)
        echo "Matched pattern2 or pattern3"
        ;;
    *)
        echo "No match"
        ;;
esac

Exit Status and Testing Commands

# Test command success
ls /tmp
if [ $? -eq 0 ]; then echo "Success"; fi
 
# Direct command testing
if grep -q "root" /etc/passwd; then
    echo "Found root"
fi

Advanced: [[ ]] Extended Test

# Pattern matching with [[ ]]
if [[ "$str" == prefix* ]]; then
    echo "Starts with prefix"
fi
 
# Regular expression matching
if [[ "$str" =~ ^[0-9]+$ ]]; then
    echo "All digits"
fi