Privacy Policy
© 2025 linux101.dev

Bash: If-Statements

The `if-statement` allows your script to make decisions based on whether a condition is true or false.

Basic If-Statement

Conditional check

if [ "$1" == "hello" ]; then
    echo "The argument is hello"
fi

The `if` block is a basic conditional check. If the condition inside the brackets is true, the commands inside the `then` block are executed.

If-Else-Statement

Using else for a fallback

if [ "$1" == "hello" ]; then
    echo "Hello, world!"
else
    echo "I do not recognize that."
fi

The `else` statement provides a fallback block of code that runs if the initial `if` condition is false.

If-Elif-Else-Statement

Multiple conditions

if [ "$1" == "hello" ]; then
    echo "Hello."
elif [ "$1" == "goodbye" ]; then
    echo "Goodbye."
else
    echo "I do not know that command."
fi

The `elif` (else if) statement allows you to check for multiple conditions in a single block.

Conditional Operators

Numeric comparisons

# Greater than
if [ "$1" -gt 10 ]; then
    echo "Greater than 10"
fi

# Less than or equal to
if [ "$1" -le 10 ]; then
    echo "Less than or equal to 10"
fi
OperatorDescription
-eqEqual to
-neNot equal to
-gtGreater than
-geGreater than or equal to
-ltLess than
-leLess than or equal to

File and directory checks

# Check if a file exists
if [ -e "/path/to/file.txt" ]; then
    echo "File exists"
fi

# Check if a directory exists
if [ -d "/path/to/directory" ]; then
    echo "Directory exists"
fi
OperatorDescription
-eFile or directory exists
-fIs a regular file
-dIs a directory
-sFile is not empty
-rFile has read permission

String patterns

if [[ "$1" == start* ]]; then
    echo "String starts with 'start'"
fi

Use double brackets `[[ ... ]]` for pattern matching with wildcards like `*`.