Bash If Else

In Bash, the if-else statement is used to perform different actions based on a condition. It allows you to execute one block of code if the condition is true, and a different block of code if the condition is false. Here’s the basic syntax of an if-else statement in Bash:

if condition
then
    # code to execute if the condition is true
else
    # code to execute if the condition is false
fi

The condition is an expression or command that evaluates to either true or false. If the condition is true, the code block following the then keyword will be executed. Otherwise, if the condition is false, the code block following the else keyword will be executed.

Here’s an example that demonstrates the usage of an if-else statement in Bash:

#!/bin/bash

number=10

if ((number > 5))
then
    echo "The number is greater than 5."
else
    echo "The number is not greater than 5."
fi

In this example, the if-else statement checks if the value of the number variable is greater than 5. If it is, the script will execute the code block following the then keyword, which outputs “The number is greater than 5.” If the condition is false, the code block following the else keyword is executed, and it outputs “The number is not greater than 5.”

When you run this script, it will output:

The number is greater than 5.

You can modify the condition and the code blocks inside the if-else statement according to your specific requirements. The if-else statement is useful when you want to execute different code paths based on a condition, providing more flexibility and control over your script’s behaviour.

Leave a Comment

Your email address will not be published. Required fields are marked *