← Back to Home

Table of Contents

Syntax

If statements in gosh follow the standard POSIX shell syntax:

Basic If Statement

if condition
then
    # commands
fi

If-Else Statement

if condition
then
    # commands when true
else
    # commands when false
fi

If-Elif-Else Statement

if condition1
then
    # commands when condition1 is true
elif condition2
then
    # commands when condition2 is true
else
    # commands when all conditions are false
fi

Features

Test Command Operators

The test command is commonly used with if statements for condition evaluation:

Numeric Comparisons

String Comparisons

File Tests

Examples

Basic Conditional Logic

#!/usr/local/bin/gosh

# Simple numeric comparison
if test 5 -gt 3
then
    echo "5 is greater than 3"
fi

# String comparison
local name="gosh"  # Local variable
if test $name = "gosh"
then
    echo "Welcome to gosh!"
else
    echo "This is not gosh"
fi

Function Argument Checking

#!/usr/local/bin/gosh

check_args() {
    if test $# -eq 0
    then
        echo "No arguments provided"
        return 1
    else
        echo "Received $# arguments"
        return 0
    fi
}

check_args
check_args arg1 arg2

File Backup Script

#!/usr/local/bin/gosh

backup_file() {
    if test $# -eq 0
    then
        echo "Usage: backup_file "
        return 1
    fi
    
    if test -f $1
    then
        local backup_name="$1.backup.$(date +%Y%m%d)"  # Local variable
        cp $1 $backup_name
        echo "Backup created: $backup_name"
    else
        echo "Error: File $1 does not exist"
        return 1
    fi
}

backup_file "important.txt"

System Information Script

#!/usr/local/bin/gosh

check_system() {
    local current_user="$(whoami)"  # Local variable
    local current_dir="$(pwd)"  # Local variable
    
    if test $current_user = "root"
    then
        echo "Warning: Running as root user"
    else
        echo "Running as user: $current_user"
    fi
    
    if test -d $current_dir
    then
        echo "Current directory: $current_dir"
        if test -w $current_dir
        then
            echo "Directory is writable"
        else
            echo "Directory is read-only"
        fi
    fi
}

check_system

Nested If Statements

#!/usr/local/bin/gosh

check_directory() {
    if test -d $1
    then
        echo "Directory $1 exists"
        if test -w $1
        then
            echo "Directory is writable"
            if test -r $1
            then
                echo "Directory is readable"
            else
                echo "Directory is not readable"
            fi
        else
            echo "Directory is read-only"
        fi
    else
        echo "Directory $1 does not exist"
    fi
}

check_directory $1

Important Notes