How to write conditional statements in bash

LinuxLinuxBeginner
Practice Now

Introduction

This comprehensive tutorial explores conditional statements in bash, a critical skill for Linux system administrators and shell script developers. By mastering bash conditionals, programmers can create more dynamic, intelligent scripts that respond effectively to different system conditions and user inputs.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL linux(("`Linux`")) -.-> linux/BasicSystemCommandsGroup(["`Basic System Commands`"]) linux/BasicSystemCommandsGroup -.-> linux/declare("`Variable Declaring`") linux/BasicSystemCommandsGroup -.-> linux/echo("`Text Display`") linux/BasicSystemCommandsGroup -.-> linux/logical("`Logic Operations`") linux/BasicSystemCommandsGroup -.-> linux/test("`Condition Testing`") linux/BasicSystemCommandsGroup -.-> linux/read("`Input Reading`") subgraph Lab Skills linux/declare -.-> lab-421283{{"`How to write conditional statements in bash`"}} linux/echo -.-> lab-421283{{"`How to write conditional statements in bash`"}} linux/logical -.-> lab-421283{{"`How to write conditional statements in bash`"}} linux/test -.-> lab-421283{{"`How to write conditional statements in bash`"}} linux/read -.-> lab-421283{{"`How to write conditional statements in bash`"}} end

Bash Conditional Basics

Introduction to Conditional Statements

Conditional statements are fundamental to programming in Bash, allowing scripts to make decisions and control program flow based on specific conditions. In Linux shell scripting, these statements help create dynamic and intelligent scripts that can respond to different scenarios.

Basic Conditional Structure

In Bash, conditional statements primarily use the if-then-else syntax. The basic structure looks like this:

if [ condition ]; then
    ## Commands to execute if condition is true
else
    ## Commands to execute if condition is false
fi

Types of Conditional Checks

Bash provides multiple ways to perform conditional checks:

1. File-based Conditions

## Check if file exists
if [ -f /path/to/file ]; then
    echo "File exists"
fi

## Check if directory exists
if [ -d /path/to/directory ]; then
    echo "Directory exists"
fi

2. String Comparisons

name="LabEx"
if [ "$name" == "LabEx" ]; then
    echo "Name matches"
fi

## Check for empty string
if [ -z "$variable" ]; then
    echo "Variable is empty"
fi

3. Numeric Comparisons

age=25
if [ $age -gt 18 ]; then
    echo "Adult"
else
    echo "Minor"
fi

Conditional Operators

Operator Description Example
-eq Equal to (numeric) [ 5 -eq 5 ]
-ne Not equal to (numeric) [ 5 -ne 6 ]
-gt Greater than [ 10 -gt 5 ]
-lt Less than [ 5 -lt 10 ]
== Equal to (string) [ "$a" == "$b" ]
!= Not equal to (string) [ "$a" != "$b" ]

Logical Operators

## AND operator
if [ condition1 ] && [ condition2 ]; then
    echo "Both conditions are true"
fi

## OR operator
if [ condition1 ] || [ condition2 ]; then
    echo "At least one condition is true"
fi

Flow Visualization

graph TD A[Start] --> B{Condition Check} B -->|True| C[Execute True Block] B -->|False| D[Execute False Block] C --> E[Continue] D --> E

Best Practices

  • Always quote variables to prevent word splitting
  • Use [[ ]] for more advanced conditional testing
  • Keep conditions simple and readable
  • Test scripts thoroughly in environments like LabEx

Test Operators and Syntax

Understanding Test Command Syntax

In Bash, conditional testing is primarily performed using the test command, which can be written in two equivalent syntaxes:

  1. Traditional syntax: test condition
  2. Bracket syntax: [ condition ]

File Test Operators

Basic File Existence and Permissions

## Check file existence
test -e /path/to/file
[ -e /path/to/file ]

## Check if file is readable
[ -r /path/to/file ]

## Check if file is writable
[ -w /path/to/file ]

## Check if file is executable
[ -x /path/to/file ]

File Type and Attributes

Operator Description Example
-f Regular file [ -f file.txt ]
-d Directory [ -d /home/user ]
-L Symbolic link [ -L symlink ]
-s File with size > 0 [ -s large_file.txt ]

String Test Operators

## Compare strings
name="LabEx"
[ "$name" = "LabEx" ]  ## Equal
[ "$name" != "Other" ]  ## Not equal

## Check string length
[ -z "$empty_var" ]    ## Zero length
[ -n "$non_empty_var" ]  ## Non-zero length

Numeric Comparison Operators

## Numeric comparisons
a=10
b=20
[ $a -eq $b ]  ## Equal
[ $a -ne $b ]  ## Not equal
[ $a -lt $b ]  ## Less than
[ $a -le $b ]  ## Less or equal
[ $a -gt $b ]  ## Greater than
[ $a -ge $b ]  ## Greater or equal

Advanced Conditional Testing

Double Bracket [[ ]] Syntax

## Enhanced string matching
if [[ "$string" =~ ^[0-9]+$ ]]; then
    echo "String is numeric"
fi

## Improved pattern matching
if [[ "$filename" == *.txt ]]; then
    echo "Text file detected"
fi

Logical Operators

## AND operation
if [ condition1 ] && [ condition2 ]; then
    echo "Both conditions true"
fi

## OR operation
if [ condition1 ] || [ condition2 ]; then
    echo "At least one condition true"
fi

Conditional Flow Visualization

graph TD A[Start Test] --> B{Condition Check} B -->|True| C[Execute True Block] B -->|False| D[Execute False Block] C --> E[Continue] D --> E

Best Practices

  • Use [[ ]] for more robust testing
  • Always quote variables
  • Understand the difference between single and double brackets
  • Test scripts in environments like LabEx for reliability

Common Pitfalls

  • Forgetting to quote variables
  • Mixing numeric and string comparisons
  • Incorrect operator usage
  • Not handling edge cases

Practical Conditional Logic

Real-World Conditional Scenarios

Conditional logic is crucial for creating intelligent and responsive Bash scripts. This section explores practical applications of conditional statements in everyday system administration and scripting tasks.

File and Directory Management

Backup Script with Conditional Checks

#!/bin/bash

BACKUP_DIR="/home/user/backups"
SOURCE_DIR="/home/user/documents"

## Create backup directory if it doesn't exist
if [ ! -d "$BACKUP_DIR" ]; then
    mkdir -p "$BACKUP_DIR"
    echo "Backup directory created"
fi

## Check if source directory has files
if [ "$(ls -A $SOURCE_DIR)" ]; then
    ## Perform backup
    cp -r "$SOURCE_DIR"/* "$BACKUP_DIR"
    echo "Backup completed successfully"
else
    echo "No files to backup"
fi

User Authentication and Permission Handling

User Access Control Script

#!/bin/bash

check_user_access() {
    local username=$1
    
    ## Check if user exists
    if id "$username" &>/dev/null; then
        ## Check user's group membership
        if groups "$username" | grep -q "admin"; then
            echo "$username has admin access"
            return 0
        else
            echo "$username has limited access"
            return 1
        fi
    else
        echo "User $username does not exist"
        return 2
    fi
}

## Example usage
check_user_access "labex_user"

System Resource Monitoring

Disk Space Alert Script

#!/bin/bash

check_disk_space() {
    local threshold=90
    local usage=$(df -h / | awk '/\// {print $(NF-1)}' | sed 's/%//')

    if [ "$usage" -gt "$threshold" ]; then
        echo "ALERT: Disk space usage is critical!"
        echo "Current usage: $usage%"
        ## Send notification or trigger cleanup
    else
        echo "Disk space is within acceptable limits"
    fi
}

check_disk_space

Conditional Flow Strategies

Multiple Condition Handling

#!/bin/bash

evaluate_system_status() {
    local cpu_load=$(uptime | awk '{print $10}' | cut -d, -f1)
    local memory_usage=$(free | grep Mem | awk '{print $3/$2 * 100.0}')

    if (( $(echo "$cpu_load > 0.8" | bc -l) )) && \
       (( $(echo "$memory_usage > 90" | bc -l) )); then
        echo "CRITICAL: High CPU and Memory Usage"
    elif (( $(echo "$cpu_load > 0.5" | bc -l) )); then
        echo "WARNING: High CPU Load"
    elif (( $(echo "$memory_usage > 70" | bc -l) )); then
        echo "WARNING: High Memory Usage"
    else
        echo "System resources are stable"
    fi
}

evaluate_system_status

Conditional Logic Visualization

graph TD A[Start Condition Check] --> B{Multiple Conditions} B -->|Condition 1| C[Action 1] B -->|Condition 2| D[Action 2] B -->|Condition 3| E[Action 3] B -->|Default| F[Default Action]

Advanced Conditional Techniques

Technique Description Use Case
Case Statements Multiple condition matching Complex input validation
Nested Conditions Hierarchical logic Intricate decision trees
Short-circuit Evaluation Efficient conditional checking Performance optimization

Best Practices for Practical Conditional Logic

  • Use meaningful variable names
  • Add comprehensive error handling
  • Log critical decisions
  • Test scripts in environments like LabEx
  • Keep conditions simple and readable

Common Practical Applications

  • Automated system maintenance
  • User access management
  • Resource monitoring
  • Backup and recovery scripts
  • Configuration management

Summary

Understanding conditional statements is fundamental to advanced bash scripting in Linux environments. This tutorial has equipped you with essential knowledge of test operators, syntax variations, and practical conditional logic techniques that will empower you to write more robust and intelligent shell scripts.

Other Linux Tutorials you may like