How to combine conditions in shell scripts

LinuxLinuxBeginner
Practice Now

Introduction

In the world of Linux shell scripting, understanding how to combine conditions is crucial for creating robust and efficient scripts. This tutorial will guide you through the process of using logical operators to build complex conditional statements, helping developers write more sophisticated and intelligent shell scripts.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL linux(("`Linux`")) -.-> linux/BasicSystemCommandsGroup(["`Basic System Commands`"]) linux(("`Linux`")) -.-> linux/TextProcessingGroup(["`Text Processing`"]) linux/BasicSystemCommandsGroup -.-> linux/echo("`Text Display`") linux/BasicSystemCommandsGroup -.-> linux/logical("`Logic Operations`") linux/BasicSystemCommandsGroup -.-> linux/test("`Condition Testing`") linux/BasicSystemCommandsGroup -.-> linux/read("`Input Reading`") linux/BasicSystemCommandsGroup -.-> linux/printf("`Text Formatting`") linux/TextProcessingGroup -.-> linux/expr("`Evaluate Expressions`") subgraph Lab Skills linux/echo -.-> lab-434167{{"`How to combine conditions in shell scripts`"}} linux/logical -.-> lab-434167{{"`How to combine conditions in shell scripts`"}} linux/test -.-> lab-434167{{"`How to combine conditions in shell scripts`"}} linux/read -.-> lab-434167{{"`How to combine conditions in shell scripts`"}} linux/printf -.-> lab-434167{{"`How to combine conditions in shell scripts`"}} linux/expr -.-> lab-434167{{"`How to combine conditions in shell scripts`"}} end

Condition Basics

Understanding Conditions in Shell Scripting

In shell scripting, conditions are fundamental for creating logical decision-making processes. They allow scripts to evaluate expressions and make choices based on specific criteria. In Linux shell environments, particularly Bash, conditions are typically evaluated using test commands or conditional expressions.

Test Command Syntax

The most common way to create conditions is using the test command, which can be written in two equivalent forms:

  1. Explicit test command:
test condition
  1. Bracket notation (preferred):
[ condition ]

Basic Comparison Operators

Shell scripts support various comparison operators for different data types:

Operator Numeric Comparison String Comparison Description
-eq Equal - Numeric equality
-ne Not equal - Numeric inequality
-gt Greater than - Numeric comparison
-lt Less than - Numeric comparison
= - String equality String comparison
!= - String inequality String comparison

File Test Operators

Shell scripts provide powerful file test operators to check file attributes:

Operator Description
-e File exists
-f Regular file exists
-d Directory exists
-r File is readable
-w File is writable
-x File is executable

Simple Condition Example

Here's a basic example demonstrating condition usage:

#!/bin/bash

## Check if a number is greater than 10
number=15

if [ $number -gt 10 ]; then
    echo "Number is greater than 10"
else
    echo "Number is 10 or less"
fi

Flow Visualization

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

Best Practices

  • Always use [ ] for conditions in modern shell scripts
  • Add spaces inside the brackets
  • Use appropriate comparison operators
  • Test scripts thoroughly

By understanding these condition basics, you'll be well-prepared to write more complex and intelligent shell scripts. LabEx recommends practicing these concepts to build solid scripting skills.

Logical Operators

Introduction to Logical Operators

Logical operators are essential for combining multiple conditions in shell scripts, allowing complex decision-making and conditional logic. In Bash, there are three primary logical operators: AND, OR, and NOT.

Logical Operators Overview

Operator Symbol Description Syntax
AND -a or && Both conditions must be true [ condition1 -a condition2 ]
OR -o or || At least one condition must be true [ condition1 -o condition2 ]
NOT ! Negates the condition [ ! condition ]

AND Operator Examples

Traditional AND Operator (-a)

#!/bin/bash

age=25
name="John"

if [ $age -gt 18 -a "$name" = "John" ]; then
    echo "Condition satisfied: Adult named John"
fi

Modern AND Operator (&&)

#!/bin/bash

[ $age -gt 18 ] && [ "$name" = "John" ] && echo "Condition satisfied"

OR Operator Examples

Traditional OR Operator (-o)

#!/bin/bash

status=1
user="admin"

if [ $status -eq 0 -o "$user" = "admin" ]; then
    echo "Access granted"
fi

Modern OR Operator (||)

#!/bin/bash

[ $status -eq 0 ] || [ "$user" = "admin" ] || echo "Access denied"

NOT Operator Example

#!/bin/bash

file="/etc/passwd"

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

Logical Operators Flow

graph TD A[Start] --> B{First Condition} B -->|True| C{Second Condition} B -->|False| D{Logical Operator} D -->|AND| E[Entire Condition False] D -->|OR| F[Check Next Condition] C -->|True| G[Condition Satisfied] C -->|False| H[Condition Not Satisfied]

Combining Multiple Conditions

#!/bin/bash

age=25
is_student=true
has_discount=false

if [ $age -lt 30 -a "$is_student" = true -a "$has_discount" = false ]; then
    echo "Eligible for special offer"
fi

Best Practices

  • Use && and || for more readable code
  • Always quote variables to prevent unexpected behavior
  • Test complex conditions carefully
  • Use parentheses for complex logical expressions

LabEx recommends practicing these logical operators to enhance your shell scripting skills and create more sophisticated conditional logic.

Practical Examples

Real-World Scenario Demonstrations

Shell scripting conditions become powerful when applied to practical scenarios. This section explores comprehensive examples that showcase condition combinations in real-world situations.

System Health Monitoring Script

#!/bin/bash

## Check disk space and memory usage
disk_usage=$(df -h / | awk '/\// {print $5}' | sed 's/%//')
memory_usage=$(free | grep Mem | awk '{print $3/$2 * 100.0}')

if [ $disk_usage -gt 80 -o $(printf "%.0f" $memory_usage) -gt 85 ]; then
    echo "ALERT: System resources critically low"
    echo "Disk Usage: $disk_usage%"
    echo "Memory Usage: $(printf "%.0f")%"
fi

User Authentication Workflow

#!/bin/bash

validate_user() {
    local username=$1
    local password=$2

    ## Complex authentication conditions
    if [ -n "$username" ] && [ -n "$password" ] && 
       [ ${#password} -ge 8 ] && 
       [[ "$password" =~ [A-Z] ]] && 
       [[ "$password" =~ [0-9] ]]; then
        return 0
    else
        return 1
    fi
}

## Usage example
validate_user "labex_user" "StrongPass123"
if [ $? -eq 0 ]; then
    echo "Authentication Successful"
else
    echo "Authentication Failed"
fi

Backup Management Script

#!/bin/bash

backup_directory() {
    local source_dir=$1
    local backup_dir=$2

    ## Multiple condition checks
    if [ -d "$source_dir" ] && [ -w "$backup_dir" ] && [ "$(ls -A $source_dir)" ]; then
        tar -czf "$backup_dir/backup_$(date +%Y%m%d).tar.gz" "$source_dir"
        return 0
    else
        echo "Backup conditions not met"
        return 1
    fi
}

Condition Workflow Visualization

graph TD A[Start Script] --> B{Condition 1} B -->|True| C{Condition 2} B -->|False| D[Exit/Error Handling] C -->|True| E{Condition 3} C -->|False| D E -->|True| F[Execute Primary Action] E -->|False| D

Advanced Condition Evaluation Matrix

Scenario Condition 1 Condition 2 Result Action
Low Disk Space Disk > 80% - Warning Alert
High Memory Memory > 85% - Warning Alert
Complex Auth Username Valid Password Complex Success Login
Backup Ready Source Exists Destination Writable Backup Compress

Error Handling with Conditions

#!/bin/bash

process_file() {
    local file=$1

    ## Comprehensive file processing conditions
    if [ ! -f "$file" ]; then
        echo "Error: File not found"
        return 1
    fi

    if [ ! -r "$file" ]; then
        echo "Error: File not readable"
        return 2
    fi

    ## File processing logic
    echo "Processing file: $file"
}

Best Practices for Practical Scripting

  • Always validate input conditions
  • Use meaningful error messages
  • Implement comprehensive checks
  • Test scripts with various scenarios

LabEx recommends developing a systematic approach to condition evaluation, focusing on robust and flexible scripting techniques.

Summary

By mastering the techniques of combining conditions in Linux shell scripts, developers can create more powerful and flexible scripts. Understanding logical operators and their practical applications enables more precise control flow, making shell scripting a more effective tool for system automation and programming tasks.

Other Linux Tutorials you may like