Linux If, Else If, Else, And More Examples

Linux Bash Programming top 10 examples

Example 1: If Statement to compare string

color="blue"

if [ "$color" == "blue" ]; then
    echo "The color is blue."
else
    echo "The color is not blue."
fi

This Bash code is a simple example of an if statement that checks the value of the variable color and prints a message based on its value. Here’s the breakdown:

  1. color="blue": This line assigns the value “blue” to the variable named color.
  2. if [ "$color" == "blue" ]; then: This line initiates an if statement. It checks if the value of the variable color is equal to the string “blue”. The [ "$color" == "blue" ] part is a conditional expression enclosed within square brackets. The double quotes around $color ensure that the variable’s value is treated as a single entity.
  3. echo "The color is blue.": If the condition in the if statement is true (meaning the value of color is indeed “blue”), this line is executed, and it prints the message “The color is blue.”
  4. else: If the condition in the if statement is false (meaning the value of color is not “blue”), the script will skip to this line.
  5. echo "The color is not blue.": In the else block, this line is executed, and it prints the message “The color is not blue.”
  6. fi: This keyword marks the end of the if statement.

So, the purpose of this code is to check if the value of the color variable is “blue” and then print a corresponding message. If the value is “blue”, it outputs “The color is blue.” If the value is anything other than “blue”, it outputs “The color is not blue.”

Output:

rahil@WorkPC:~/scripts$ touch example1.sh
rahil@WorkPC:~/scripts$ vi example1.sh        # Copy and paste above code
rahil@WorkPC:~/scripts$ chmod 755 example1.sh
rahil@WorkPC:~/scripts$ bash example1.sh
The color is blue.
rahil@WorkPC:~/scripts$

Example 2: If statement to compare numbers.

#!/bin/bash

num1=10
num2=20

if [ $num1 -eq $num2 ]; then
    echo "The numbers are equal."
else
    echo "The numbers are not equal."
fi

This Bash code demonstrates an if statement that compares two numeric variables, num1 and num2, and prints a message based on whether they are equal. Let’s break it down step by step:

  1. num1=10 and num2=20: These lines initialize two variables, num1 with a value of 10 and num2 with a value of 20.
  2. if [ $num1 -eq $num2 ]; then: This line starts an if statement. It checks if the value of num1 is equal to the value of num2. The -eq operator is used for numeric equality comparison.
  3. echo "The numbers are equal.": If the condition inside the if statement is true (meaning num1 is indeed equal to num2), this line is executed, and it prints the message “The numbers are equal.”
  4. else: If the condition inside the if statement is false (meaning num1 is not equal to num2), the script will skip to this line.
  5. echo "The numbers are not equal.": In the else block, this line is executed, and it prints the message “The numbers are not equal.”
  6. fi: This keyword marks the end of the if statement.

So, when you run the script, it will compare the values of num1 and num2 (which are 10 and 20, respectively). Since they are not equal, the script will output “The numbers are not equal.”

Example 3: if statement on less than an x number

#!/bin/bash

score=85
passing_score=70

if [ $score -lt $passing_score ]; then
    echo "You did not pass."
else
    echo "Congratulations, you passed!"
fi

In this example, the -lt operator is used to check if the value of the variable score is less than the value of passing_score. If score is indeed less than passing_score, the script will output “You did not pass.” Otherwise, it will output “Congratulations, you passed!”

Example 4: If statement with logical AND operator

Here’s an example of an if statement in Bash that uses the logical AND (&&) operator to combine two conditions:

#!/bin/bash

age=25
has_license=true

if [ $age -ge 18 ] && [ "$has_license" = true ]; then
    echo "You are eligible to drive."
else
    echo "You are not eligible to drive."
fi

Explanation:
In this example, the script checks two conditions using the logical AND (&&) operator within the if statement:

  1. [ $age -ge 18 ]: This condition checks if the variable age is greater than or equal to 18. If this condition is true, it means the person is of legal driving age.
  2. [ "$has_license" = true ]: This condition checks if the variable has_license is equal to the string “true”. The double quotes around $has_license ensure that the value is treated as a single entity.

The logical AND operator && combines these conditions. The if statement evaluates whether both conditions are true. If both conditions are true, the script will output “You are eligible to drive.” If either of the conditions is false, it will output “You are not eligible to drive.”

Using the logical AND operator in this manner allows you to make decisions based on multiple conditions, ensuring that both conditions must be true for the if block to execute.

Example 5: If statement with logical OR operator

Here’s an example of an if statement in Bash that uses the logical OR (||) operator to combine two conditions:

#!/bin/bash

temperature=28
is_raining=true

if [ $temperature -gt 30 ] || [ "$is_raining" = true ]; then
    echo "It's a good day to stay indoors."
else
    echo "It's a nice day to go outside."
fi

Explanation:
In this example, the script checks two conditions using the logical OR (||) operator within the if statement:

  1. [ $temperature -gt 30 ]: This condition checks if the variable temperature is greater than 30. If this condition is true, it indicates a hot day.
  2. [ "$is_raining" = true ]: This condition checks if the variable is_raining is equal to the string “true”.

The logical OR operator || combines these conditions. The if statement evaluates whether either of the conditions is true. If either condition is true (i.e., it’s either a hot day or it’s raining), the script will output “It’s a good day to stay indoors.” If both conditions are false, it will output “It’s a nice day to go outside.”

Using the logical OR operator in this manner allows you to make decisions based on multiple conditions, ensuring that at least one of the conditions must be true for the if block to execute.

Example 6: If then statement

The if statement in Bash is used for conditional execution. It allows you to specify a condition, and if that condition evaluates to true, a certain block of code is executed. Here’s the basic syntax of an if statement:

if [ condition ]; then
    # Code to be executed if the condition is true
fi

Here’s an example to help you understand how the if statement works:

#!/bin/bash

age=20

if [ $age -ge 18 ]; then
    echo "You are eligible to vote."
fi

Explanation:

  1. age=20: This line assigns the value 20 to the variable age.
  2. if [ $age -ge 18 ]; then: This line starts the if statement. The condition [ $age -ge 18 ] checks if the value of age is greater than or equal to 18.
  3. echo "You are eligible to vote.": If the condition is true (which it is in this case because age is 20), this line is executed, and it prints the message “You are eligible to vote.”
  4. fi: This keyword marks the end of the if statement.

In this example, the if statement checks whether the value of the age variable is greater than or equal to 18. Since 20 is indeed greater than 18, the condition is true, and the message “You are eligible to vote.” is printed to the console. If the condition were false, the message would not be printed.

Example 7: Elif statement

The elif statement in Bash is used to add an additional condition to the if statement. If the initial if condition is false, the script checks the elif condition. If the elif condition is true, a different block of code is executed. Here’s the basic syntax of an if statement with elif:

if [ condition1 ]; then
    # Code to be executed if condition1 is true
elif [ condition2 ]; then
    # Code to be executed if condition2 is true
else
    # Code to be executed if both condition1 and condition2 are false
fi

Here’s an example to help you understand how the elif statement works:

#!/bin/bash

age=15

if [ $age -ge 18 ]; then
    echo "You are eligible to vote."
elif [ $age -ge 16 ]; then
    echo "You can apply for a driving license."
else
    echo "You are too young for these privileges."
fi

Explanation:

  1. age=15: This line assigns the value 15 to the variable age.
  2. if [ $age -ge 18 ]; then: This line starts the if statement. The condition [ $age -ge 18 ] checks if the value of age is greater than or equal to 18.
  3. echo "You are eligible to vote.": If the condition in the if statement is true, this line is executed, and it prints the message “You are eligible to vote.”
  4. elif [ $age -ge 16 ]; then: If the condition in the if statement is false, the script moves to the elif statement. Here, the condition [ $age -ge 16 ] checks if the value of age is greater than or equal to 16.
  5. echo "You can apply for a driving license.": If the elif condition is true, this line is executed, and it prints the message “You can apply for a driving license.”
  6. else: If both the if and elif conditions are false, the script moves to the else block.
  7. echo "You are too young for these privileges.": In the else block, this line is executed, and it prints the message “You are too young for these privileges.”

In this example, the script checks different age-related conditions using the if, elif, and else statements, and it prints appropriate messages based on the age provided.

Example 8: Shorthand version of if-else

Certainly! In Bash, you can use a shorthand version of the if statement when you have a single command to execute based on a condition. This is often called the ternary operator. Here’s the syntax:

[ condition ] && command_if_true || command_if_false

Explanation:

  • [ condition ]: This is the condition you want to check. It can be any valid shell expression.
  • &&: This is the logical AND operator. If the condition is true, the command following it will be executed.
  • command_if_true: This is the command that will be executed if the condition is true.
  • ||: This is the logical OR operator. If the condition is false, the command following it will be executed.
  • command_if_false: This is the command that will be executed if the condition is false.

Here’s an example:

#!/bin/bash

age=20

[ $age -ge 18 ] && echo "You are eligible to vote." || echo "You are not eligible to vote."

Explanation:
In this example, the script checks whether the value of the age variable is greater than or equal to 18. If the condition is true, it executes the command echo "You are eligible to vote.". If the condition is false, it executes the command echo "You are not eligible to vote.".

This shorthand version of the if statement can be useful for simple conditional actions that involve executing a single command based on the condition’s outcome.

Example 9: If-elif, else-if with user numeric input example

#!/bin/bash
read -p "Please enter a value: " INPUT_VALUE
if [[ $INPUT_VALUE -lt 0 ]]; then
     echo "Negative value provided."
elif [[ $INPUT_VALUE -ge 0 && $INPUT_VALUE -lt 10 ]]; then
     echo "The value is between 0 and 9 (inclusive)."
elif [[ $INPUT_VALUE -ge 10 && $INPUT_VALUE -lt 100 ]]; then
     echo "The value is a two-digit number."
else
     echo "The value is outside the valid range."
fi

The provided Bash code is an example of a script that takes user input and uses conditional statements to determine characteristics of the input value. Here’s a detailed explanation of each part of the code:

  1. #!/bin/bash: This is called a shebang and indicates that the script should be interpreted using the Bash shell.
  2. read -p "Please enter a value: " INPUT_VALUE: This line prompts the user to input a value and assigns the input to the variable INPUT_VALUE.
  3. if [[ $INPUT_VALUE -lt 0 ]]; then: This is the start of the if statement. It checks whether the value stored in the INPUT_VALUE variable is less than 0.
  4. echo "Negative value provided.": If the condition in the previous line is true (meaning the input value is negative), this line is executed, and it prints the message “Negative value provided.”
  5. elif [[ $INPUT_VALUE -ge 0 && $INPUT_VALUE -lt 10 ]]; then: If the condition in the if statement is false, the script moves to the elif statement. This line checks if the value of INPUT_VALUE is greater than or equal to 0 and less than 10.
  6. echo "The value is between 0 and 9 (inclusive).": If the condition in the elif statement is true (meaning the input value is between 0 and 9), this line is executed, and it prints the message “The value is between 0 and 9 (inclusive).”
  7. elif [[ $INPUT_VALUE -ge 10 && $INPUT_VALUE -lt 100 ]]; then: If the second condition is false, the script moves to the next elif statement. This line checks if the value of INPUT_VALUE is greater than or equal to 10 and less than 100.
  8. echo "The value is a two-digit number.": If the condition in the second elif statement is true (meaning the input value is a two-digit number), this line is executed, and it prints the message “The value is a two-digit number.”
  9. else: If none of the conditions above are true, the script reaches the else block.
  10. echo "The value is outside the valid range.": In the else block, this line is executed, and it prints the message “The value is outside the valid range.”
  11. fi: This keyword marks the end of the if statement.

This script takes user input, checks its value against different conditions, and provides output messages accordingly. It showcases the use of if, elif, and else statements to perform conditional branching based on the value of the INPUT_VALUE variable.

Example 10: if-else-then-elfi advance programming example

Here’s an advanced example of using nested if, else, then, and elif statements in Bash programming:

#!/bin/bash

read -p "Enter your age: " age

if [ $age -ge 18 ]; then
    echo "You are an adult."

    read -p "Do you have a driver's license? (yes/no): " has_license

    if [ "$has_license" = "yes" ]; then
        echo "You can drive."
    elif [ "$has_license" = "no" ]; then
        echo "You cannot drive."
    else
        echo "Invalid input for license status."
    fi

else
    echo "You are a minor."

    read -p "Are you in school? (yes/no): " is_in_school

    if [ "$is_in_school" = "yes" ]; then
        echo "You are a student."
    elif [ "$is_in_school" = "no" ]; then
        echo "You are not a student."
    else
        echo "Invalid input for school status."
    fi

fi

Explanation:
In this advanced example, the script takes user input for their age and then uses nested if and else statements to gather more information based on the age category. Here’s how it works:

  1. The user is prompted to enter their age.
  2. The outer if statement checks if the age is greater than or equal to 18. If true, it means the user is an adult.
  3. If the user is an adult, they are asked whether they have a driver’s license. The nested if statement inside the then block checks their response and provides an appropriate message.
  4. If the user is not an adult (age less than 18), the script enters the else block and considers them a minor.
  5. For minors, the user is asked whether they are in school. The nested if statement inside the else block checks their response and provides an appropriate message.
  6. The elif statements handle cases where the user provides unexpected input (“yes” or “no” responses are expected).

This example showcases how to use nested if, else, then, and elif statements to create more complex decision-making structures based on user input and different conditions.

Leave a Comment

Scroll to Top