Introduction

Hello! In this article, we’ll learn about if statements.

if is a construct for conditional branching. Used when writing processing like “if XX then do YY”. If you’ve done any programming, this should be familiar.

What is an if Statement?

if is a control structure for changing processing based on conditions.

“Delete if file exists”, “warn if variable is empty” - when you want to branch processing based on conditions, you use this.

Basic Syntax

Basic Form

1
2
3
if [ condition ]; then
    # Processing when condition is true
fi

With else

1
2
3
4
5
if [ condition ]; then
    # Processing when condition is true
else
    # Processing when condition is false
fi

With elif (Multiple Conditions)

1
2
3
4
5
6
7
if [ condition1 ]; then
    # Processing when condition1 is true
elif [ condition2 ]; then
    # Processing when condition2 is true
else
    # Processing when all conditions are false
fi

Commonly Used Conditional Expressions

String Comparison

Expression Meaning
[ "$a" = "$b" ] Strings are equal
[ "$a" != "$b" ] Strings are not equal
[ -z "$a" ] String is empty
[ -n "$a" ] String is not empty

Numeric Comparison

Expression Meaning
[ $a -eq $b ] Equal
[ $a -ne $b ] Not equal
[ $a -gt $b ] Greater than
[ $a -lt $b ] Less than
[ $a -ge $b ] Greater or equal
[ $a -le $b ] Less or equal

File/Directory Check

Expression Meaning
[ -f "$file" ] File exists
[ -d "$dir" ] Directory exists
[ -e "$path" ] File or directory exists
[ -r "$file" ] Readable
[ -w "$file" ] Writable
[ -x "$file" ] Executable

Usage Examples

Example 1: Basic Usage

1
2
3
4
5
age=20

if [ $age -ge 18 ]; then
    echo "Adult"
fi

Output:

1
Adult

Example 2: Using else

1
2
3
4
5
6
7
age=15

if [ $age -ge 18 ]; then
    echo "Adult"
else
    echo "Minor"
fi

Output:

1
Minor

Example 3: Using elif (Multiple Conditions)

1
2
3
4
5
6
7
8
9
score=75

if [ $score -ge 80 ]; then
    echo "Excellent"
elif [ $score -ge 60 ]; then
    echo "Pass"
else
    echo "Fail"
fi

Output:

1
Pass

Example 4: File Existence Check

1
2
3
4
5
6
7
file="test.txt"

if [ -f "$file" ]; then
    echo "$file exists"
else
    echo "$file does not exist"
fi

Example 5: String Comparison

1
2
3
4
5
6
7
read -p "Enter password: " password

if [ "$password" = "secret" ]; then
    echo "Login successful"
else
    echo "Wrong password"
fi

Example 6: Empty String Check

1
2
3
4
5
6
7
read -p "Enter name: " name

if [ -z "$name" ]; then
    echo "Name not entered"
else
    echo "Hello, ${name}"
fi

Tips & Notes

  • Spaces around [ ]: Must have spaces before and after [ and ]

    1
    2
    
    if [ $a -eq 1 ]; then  # Correct
    if [$a -eq 1]; then    # Error!
    
  • Quote variables: Variables should be enclosed in double quotes

    1
    2
    
    if [ "$var" = "test" ]; then  # Correct
    if [ $var = "test" ]; then    # May error when variable is empty
    
  • [[ ]] also available: Bash-specific but [[ ]] also works (more convenient)

    1
    2
    3
    
    if [[ $a == "test" ]]; then
        echo "Match"
    fi
    
  • Multiple conditions with && and ||: AND and OR conditions

    1
    2
    3
    4
    5
    6
    7
    8
    9
    
    # AND (both true)
    if [ $a -gt 0 ] && [ $a -lt 10 ]; then
        echo "Range 1-9"
    fi
    
    # OR (either true)
    if [ $a -eq 1 ] || [ $a -eq 2 ]; then
        echo "1 or 2"
    fi
    
  • Negation with !: Invert condition

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

Practical Usage

File Backup Script

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
#!/bin/bash

file="important.txt"
backup="${file}.bak"

if [ -f "$file" ]; then
    cp "$file" "$backup"
    echo "Backup created: $backup"
else
    echo "Error: $file not found"
fi

Argument Check

1
2
3
4
5
6
7
8
#!/bin/bash

if [ $# -eq 0 ]; then
    echo "Usage: $0 <filename>"
    exit 1
fi

echo "Starting process: $1"

Create Directory (Only if Not Exists)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
#!/bin/bash

dir="backup"

if [ ! -d "$dir" ]; then
    mkdir "$dir"
    echo "Created directory: $dir"
else
    echo "Directory already exists: $dir"
fi

Combining Multiple Conditions

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
#!/bin/bash

read -p "Username: " user
read -sp "Password: " pass
echo

if [ "$user" = "admin" ] && [ "$pass" = "secret" ]; then
    echo "Logged in as administrator"
elif [ -n "$user" ] && [ -n "$pass" ]; then
    echo "Logged in as regular user"
else
    echo "Login failed"
fi

Summary

In this article, we learned about if statements.

Key Points:

  • Branch processing with conditions using if
  • Must have spaces before and after [ ]
  • Enclose variables in double quotes
  • Various conditions available: file checks, numeric comparisons, etc.

When writing shell scripts, if statements are absolutely fundamental. The syntax might feel a bit unfamiliar at first, but you’ll get used to it with practice.

Keep learning Linux commands!