Bash if Conditions: A Comprehensive Guide

# **Bash `if` Conditions: A Comprehensive Guide**  

This document explains how to use `if` conditions in Bash scripting, covering common scenarios with examples.  

---

## **1. Basic `if`, `else`, `else if` (`elif`)**  
### **Syntax:**
```bash
if [ condition ]; then
    # Code if condition is true
elif [ another_condition ]; then
    # Code if another_condition is true
else
    # Code if all conditions are false
fi
```
### **Example:**
```bash
read -p "Enter a number: " num

if [ "$num" -gt 10 ]; then
    echo "Greater than 10"
elif [ "$num" -eq 10 ]; then
    echo "Exactly 10"
else
    echo "Less than 10"
fi
```

---

## **2. `if` with AND (`&&`) / OR (`||`) Conditions**  
### **Syntax:**
- **AND (`&&`)** → Both conditions must be true.  
- **OR (`||`)** → At least one condition must be true.  

### **Example:**
```bash
age=25
name="Alice"

if [ "$age" -gt 18 ] && [ "$name" == "Alice" ]; then
    echo "Welcome, Alice! You are an adult."
fi

if [ "$age" -lt 18 ] || [ "$name" == "Bob" ]; then
    echo "You are either under 18 or named Bob."
fi
```

---

## **3. `if` with Command Result Condition**  
Check if a command succeeds (`exit 0`) or fails (`exit non-zero`).  

### **Example:**
```bash
if grep -q "error" /var/log/syslog; then
    echo "Error found in logs!"
else
    echo "No errors found."
fi

# Check if a file exists
if [ -f "/etc/passwd" ]; then
    echo "File exists."
fi
```

---

## **4. `if` String Exists (or Not)**  
Check if a string is **empty** or **non-empty**.  

### **Example:**
```bash
str="Hello"

if [ -z "$str" ]; then
    echo "String is empty."
elif [ -n "$str" ]; then
    echo "String is not empty."
fi

# Check if a substring exists
if [[ "$str" == *"ell"* ]]; then
    echo "Substring 'ell' found."
fi
```

---

## **5. `if` Equal to Number (Numeric Comparison)**  
Use `-eq`, `-ne`, `-gt`, `-lt`, `-ge`, `-le`.  

### **Example:**
```bash
num=15

if [ "$num" -eq 15 ]; then
    echo "Number is 15."
elif [ "$num" -lt 10 ]; then
    echo "Number is less than 10."
fi
```

---

## **6. `if` Not Exist (Negative Conditions)**  
Check if a **file/directory does not exist** or a condition is **false**.  

### **Example:**
```bash
file="/tmp/test.txt"

if [ ! -f "$file" ]; then
    echo "File does not exist."
fi

if [ "$num" -ne 20 ]; then
    echo "Number is not 20."
fi
```

---

## **7. Other Frequently Used `if` Conditions**  

| Condition | Example | Description |
|-----------|---------|-------------|
| **Check if directory exists** | `if [ -d "/path" ]; then` | True if directory exists |
| **Check if file is readable** | `if [ -r "$file" ]; then` | True if file has read permissions |
| **Check if variable is set** | `if [ -v "$var" ]; then` | True if variable exists |
| **Check if file is executable** | `if [ -x "/bin/bash" ]; then` | True if file is executable |
| **Check if string matches regex** | `if [[ "$str" =~ ^[A-Z] ]]; then` | True if string starts with uppercase |

### **Example:**
```bash
dir="/etc"

if [ -d "$dir" ]; then
    echo "$dir is a directory."
fi

if [[ "$USER" =~ ^root$ ]]; then
    echo "You are root!"
fi
```

---

## **Summary Cheat Sheet**  
| **Condition Type** | **Syntax** |
|------------------|-----------|
| Basic `if-else` | `if [ cond ]; then ... fi` |
| AND (`&&`) | `if [ cond1 ] && [ cond2 ]; then` |
| OR (`||`) | `if [ cond1 ] \|\| [ cond2 ]; then` |
| Command Success | `if cmd; then` |
| String Exists | `if [ -n "$str" ]; then` |
| String Empty | `if [ -z "$str" ]; then` |
| Number Comparison | `if [ "$num" -eq 10 ]; then` |
| File Exists | `if [ -f "$file" ]; then` |
| Directory Exists | `if [ -d "$dir" ]; then` |
| Negative Condition | `if [ ! cond ]; then` |

---

## **Final Tips**  
✔ **Always quote variables** (`"$var"`) to avoid word splitting.  
✔ **Use `[[ ]]` for advanced string matching** (supports `==`, `=~`).  
✔ **Prefer `-eq` for numbers, `==` for strings**.