LinuxCommandLibrary

else

Execute code when 'if' condition is false

TLDR

View documentation for the if keyword

$ tldr if
copy

SYNOPSIS

if condition; then
    commands
elif condition; then
    commands
else
    commands
fi

DESCRIPTION

The `else` command in Linux is a fundamental part of conditional control flow in shell scripts. It's *not* a standalone command that can be executed directly from the command line. Instead, `else` forms a crucial element within `if` statements, providing an alternative block of code to execute when the initial `if` condition evaluates to false (i.e., a non-zero exit status). The `else` block provides a way to handle situations where the `if` condition is not met, ensuring that some action is always taken. You can chain `if` statements using `elif` (else if) to test multiple conditions. Essentially, `else` acts as a catch-all for any scenario not covered by the preceding `if` and `elif` conditions. Its role is to define what actions should occur if all other specified conditions prove false. Its proper use ensures predictable and robust script behavior, allowing for graceful handling of diverse input and runtime situations.
Its purpose is to execute a block of commands ONLY if the preceding `if` or `elif` condition failed.

CAVEATS

The `else` command *must* be used within an `if` or `elif` statement. It cannot be used as a standalone command. Syntax errors will occur if the `else` command is used without a preceding if or elif.

EXAMPLE

```bash #!/bin/bash read -p "Enter a number: " num if (( num > 10 )); then echo "The number is greater than 10." else echo "The number is not greater than 10." fi ``` This script prompts the user to enter a number. The `if` statement checks if the number is greater than 10. If it is, the first `echo` command is executed. Otherwise, the `else` block's `echo` command is executed.

ERROR HANDLING

Without an `else` statement, there's no defined action if the `if` condition fails. While this might be acceptable in some cases, using `else` is generally good practice for providing a default behavior or error message.

SEE ALSO

if(1), elif(1), fi(1), test(1), [(1)

Copied to clipboard