if Statement

The if statement is a fundamental control structure in shell scripting that allows conditional execution of commands based on the success or failure of test conditions.

Syntax

if [ condition ]
then
    commands
fi

# Alternative single-line syntax
if [ condition ]; then commands; fi

Description

The if statement evaluates a condition and executes commands based on whether the condition is true (exit status 0) or false (non-zero exit status).

Key features:

  • Conditional command execution
  • Support for else and elif clauses
  • Multiple test operators and conditions
  • Nested if statements
  • Integration with command exit codes

Common Test Operators

Operator Description Example
-eq Equal to (numeric) [ $a -eq $b ]
-ne Not equal to (numeric) [ $a -ne $b ]
-lt Less than (numeric) [ $a -lt $b ]
-le Less than or equal (numeric) [ $a -le $b ]
-gt Greater than (numeric) [ $a -gt $b ]
-ge Greater than or equal (numeric) [ $a -ge $b ]
= Equal to (string) [ "$str1" = "$str2" ]
!= Not equal to (string) [ "$str1" != "$str2" ]
-z String is empty [ -z "$str" ]
-n String is not empty [ -n "$str" ]

File Test Operators

Operator Description Example
-f File exists and is regular file [ -f file.txt ]
-d Directory exists [ -d /path/dir ]
-e File or directory exists [ -e /path/item ]
-r File is readable [ -r file.txt ]
-w File is writable [ -w file.txt ]
-x File is executable [ -x script.sh ]
-s File exists and is not empty [ -s file.txt ]

Examples

Basic if statement

if [ $USER = "root" ] then echo "You are the root user" fi

Checks if the current user is root

if-else statement

if [ -f /etc/passwd ] then echo "Password file exists" else echo "Password file not found" fi

Checks if a file exists with alternative action

if-elif-else statement

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

Multiple conditions with elif clauses

String comparison

read -p "Enter your name: " name if [ "$name" = "admin" ] then echo "Welcome, administrator!" else echo "Hello, $name" fi

Compares user input with a string

Numeric comparison

age=25 if [ $age -ge 18 ] then echo "You are an adult" else echo "You are a minor" fi

Compares numeric values

File existence check

filename="data.txt" if [ -f "$filename" ] then echo "File $filename exists" wc -l "$filename" else echo "File $filename not found" touch "$filename" fi

Checks if file exists and performs actions

Directory check

if [ -d "/home/$USER/Documents" ] then cd "/home/$USER/Documents" echo "Changed to Documents directory" else echo "Documents directory not found" fi

Checks if directory exists before changing to it

Command success check

if ping -c 1 google.com > /dev/null 2>&1 then echo "Internet connection is working" else echo "No internet connection" fi

Tests command success using exit status

Multiple conditions with logical operators

if [ $# -gt 0 ] && [ -f "$1" ] then echo "Processing file: $1" cat "$1" else echo "Usage: $0 filename" fi

Combines multiple conditions with AND operator

Empty string check

read -p "Enter password: " -s password echo if [ -z "$password" ] then echo "Password cannot be empty" else echo "Password accepted" fi

Checks if string is empty

Nested if statements

if [ -f "$1" ] then if [ -r "$1" ] then echo "File is readable" if [ -w "$1" ] then echo "File is also writable" fi else echo "File is not readable" fi else echo "File does not exist" fi

Nested conditions for complex logic

Using test command

# These are equivalent if [ -f file.txt ]; then echo "exists"; fi if test -f file.txt; then echo "exists"; fi

Alternative syntax using test command

Advanced Usage

Pattern matching

filename="document.pdf" if [[ $filename == *.pdf ]] then echo "This is a PDF file" fi

Using [[ ]] for pattern matching (bash-specific)

Regular expressions

email="[email protected]" if [[ $email =~ ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ ]] then echo "Valid email format" else echo "Invalid email format" fi

Using regular expressions with [[ ]] (bash-specific)

Common Use Cases

When to Use if Statements
  • Input Validation - Check user input and command arguments
  • File Operations - Verify file existence before processing
  • Error Handling - Handle command failures gracefully
  • Configuration - Adapt behavior based on system state
  • Flow Control - Direct script execution based on conditions

See also