Introduction
In the world of Linux system administration and programming, understanding conditional logic in shell scripting is crucial for creating flexible and intelligent scripts. This tutorial provides a comprehensive guide to constructing conditional statements in shell environments, helping developers and system administrators write more efficient and powerful shell scripts.
Shell Conditional Basics
Introduction to Conditional Statements
In shell scripting, conditional statements are fundamental for creating dynamic and intelligent scripts. They allow you to make decisions and control the flow of your program based on specific conditions.
Basic Test Operators
Shell provides several ways to evaluate conditions using test operators:
Test Command Syntax
There are two primary ways to write conditional tests:
- Using
testcommand:
test condition
- Using square brackets:
[ condition ]
Comparison Operators
| Operator | Description | Numeric Comparison | String Comparison |
|---|---|---|---|
-eq |
Equal to | ✓ | × |
-ne |
Not equal | ✓ | × |
-gt |
Greater than | ✓ | × |
-lt |
Less than | ✓ | × |
== |
Equal | × | ✓ |
!= |
Not equal | × | ✓ |
Simple Conditional Example
Here's a basic example demonstrating conditional logic:
#!/bin/bash
age=25
if [ $age -ge 18 ]; then
echo "You are an adult"
else
echo "You are a minor"
fi
Control 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
Common Conditional Scenarios
- Checking file existence
- Comparing numeric values
- Validating string contents
- Checking command execution status
Best Practices
- Always use
[ ]with spaces inside - Use
-zto check empty strings - Use
-nto check non-empty strings - Test complex conditions with
&&and||
LabEx Learning Tip
Practice these conditional techniques in LabEx's interactive Linux environments to gain hands-on experience with shell scripting.
Comparison and Logic
Logical Operators Overview
Shell scripting provides powerful logical operators to combine and evaluate multiple conditions effectively.
Logical AND and OR Operators
Logical AND (&&)
Executes the next command only if the previous command succeeds:
[ condition ] && command_if_true
Logical OR (||)
Executes the next command if the previous command fails:
[ condition ] || command_if_false
Complex Condition Evaluation
Combining Multiple Conditions
#!/bin/bash
age=25
name="John"
if [ $age -ge 18 ] && [ "$name" == "John" ]; then
echo "Adult named John"
fi
Logical Operator Truth Table
| Condition 1 | Operator | Condition 2 | Result |
|---|---|---|---|
| True | && |
True | True |
| True | && |
False | False |
| False | && |
True | False |
| False | && |
False | False |
| True | || |
True | True |
| True | || |
False | True |
| False | || |
True | True |
| False | || |
False | False |
Nested Condition Flow
graph TD
A[Start] --> B{First Condition}
B -->|True| C{Second Condition}
B -->|False| G[Exit]
C -->|True| D[Execute Action]
C -->|False| G
Advanced Condition Checking
Negation Operator (!)
Inverts the result of a condition:
if [ ! -f /path/to/file ]; then
echo "File does not exist"
fi
Comparison Types
- Numeric Comparisons
- String Comparisons
- File Test Conditions
Numeric Comparison Example
#!/bin/bash
x=10
y=20
if [ $x -lt $y ]; then
echo "x is less than y"
fi
String Comparison Example
#!/bin/bash
input="Hello"
if [ "$input" == "Hello" ]; then
echo "Greeting matches"
fi
LabEx Practical Tip
Experiment with these logical operators in LabEx's shell environment to master conditional logic techniques.
Practical Conditional Flows
Comprehensive Conditional Structures
Multiple Condition Handling
If-Elif-Else Statements
#!/bin/bash
score=85
if [ $score -ge 90 ]; then
echo "Grade: A"
elif [ $score -ge 80 ]; then
echo "Grade: B"
elif [ $score -ge 70 ]; then
echo "Grade: C"
else
echo "Grade: F"
fi
Case Statement Usage
Pattern Matching Scenarios
#!/bin/bash
read -p "Enter a day: " day
case $day in
Monday) echo "Start of workweek" ;;
Tuesday) echo "Second workday" ;;
Wednesday) echo "Midweek" ;;
Thursday) echo "Almost weekend" ;;
Friday) echo "Weekend is near" ;;
Saturday | Sunday)
echo "Weekend!"
;;
*) echo "Invalid day" ;;
esac
Conditional Flow Visualization
graph TD
A[Start] --> B{First Condition}
B -->|True| C[Action 1]
B -->|False| D{Second Condition}
D -->|True| E[Action 2]
D -->|False| F{Third Condition}
F -->|True| G[Action 3]
F -->|False| H[Default Action]
Advanced Conditional Techniques
Input Validation Script
#!/bin/bash
validate_input() {
local input=$1
if [[ -z "$input" ]]; then
echo "Error: Input cannot be empty"
return 1
fi
if [[ ! "$input" =~ ^[0-9]+$ ]]; then
echo "Error: Input must be a number"
return 1
fi
return 0
}
read -p "Enter a number: " user_input
if validate_input "$user_input"; then
echo "Valid input: $user_input"
fi
Conditional Operation Types
| Operation Type | Description | Example |
|---|---|---|
| Numeric Check | Compare numbers | -eq, -gt, -lt |
| String Check | Compare strings | ==, != |
| File Check | Test file properties | -f, -d, -x |
| Logical Check | Combine conditions | &&, || |
Error Handling with Conditions
#!/bin/bash
backup_file() {
local source=$1
local destination=$2
if [ ! -f "$source" ]; then
echo "Source file does not exist"
return 1
fi
cp "$source" "$destination" || {
echo "Backup failed"
return 1
}
echo "Backup successful"
return 0
}
backup_file "/etc/passwd" "/tmp/passwd.bak"
LabEx Learning Strategy
Practice these conditional flow techniques in LabEx's interactive shell environments to develop robust scripting skills.
Summary
By mastering conditional logic in Linux shell scripting, developers can create more dynamic and responsive scripts that can make intelligent decisions based on system conditions, file states, and variable comparisons. The techniques covered in this tutorial provide a solid foundation for writing robust and adaptable shell scripts that can handle complex computational tasks and system interactions.



