Skip to content
Bash

Conditionals

if and case conditional statements.

By EZ4Code Team
bashconditional

Code

#!/bin/bash

# if statement
if [ -f file.txt ]; then
    echo "File exists"
elif [ -d dir ]; then
    echo "Directory exists"
else
    echo "Not found"
fi

# File test
[ -f file ]    # Is regular file
[ -d dir ]     # Is directory
[ -r file ]    # Readable
[ -w file ]    # Writable
[ -x file ]    # Executable
[ -s file ]    # Non-empty file
[ -e path ]    # Exists

# String comparison
[ "$str1" = "$str2" ]   # Equal
[ "$str1" != "$str2" ]  # Not equal
[ -z "$str" ]           # Empty string
[ -n "$str" ]           # Non-empty string

# Numeric comparison
[ $n -eq 5 ]  # Equal
[ $n -ne 5 ]  # Not equal
[ $n -lt 5 ]  # Less than
[ $n -gt 5 ]  # Greater than
[ $n -le 5 ]  # Less than or equal
[ $n -ge 5 ]  # Greater than or equal

# Logical operations
if [ -f file.txt ] && [ -r file.txt ]; then
    echo "Readable file"
fi

if [ "$var" = "a" ] || [ "$var" = "b" ]; then
    echo "a or b"
fi

# case statement
case $1 in
    start)
        echo "Starting..."
        ;;
    stop)
        echo "Stopping..."
        ;;
    restart)
        echo "Restarting..."
        ;;
    *)
        echo "Usage: $0 {start|stop|restart}"
        exit 1
        ;;
esac

# Ternary (shorthand)
[ -f file.txt ] && echo "exists" || echo "not exists"

Explanation

Bash conditions use [ ] or [[ ]], supporting file tests, string and numeric comparisons; case is for multi-branch matching.

More Bash Snippets