if-else conditional statements

In shell scripting, if-else conditions allow you to execute different blocks of code based on certain conditions. The syntax for an if-else statement in shell scripting is as follows:

Syntax:

if condition
then
    # code to be executed if condition is true
else
    # code to be executed if condition is false
fi

Here’s a breakdown of how if-else conditions work:

  1. if statement: This is the starting point of the conditional block. It checks a specific condition.
  2. then keyword: This marks the beginning of the code block that will be executed if the condition is true.
  3. Code Block: The commands or code you want to execute if the condition evaluates to true. This can be a single command or a series of commands.
  4. else statement: If the condition in the if statement is false, the code after the else keyword is executed.
  5. fi statement: This marks the end of the if-else block.

Here’s an example to illustrate the usage of if-else in a shell script:

#!/bin/bash

# Prompting user for input
read -p "Enter a number: " num

if [ $num -gt 0 ]
then
    echo "The number is positive."
else
    echo "The number is non-positive."
fi

In this example, the script prompts the user to enter a number. It then checks if the number is greater than zero. If it is, it prints “The number is positive.” Otherwise, it prints “The number is non-positive.”

Keep in mind the following important points:

  • Use [ ] to denote the condition. The spaces around the square brackets are important.
  • Ensure there’s a space after if, then, else, and before fi.
  • The condition can be any valid shell expression, and it’s evaluated within the [ ].

You can also have multiple conditions using elif (short for “else if”) statements:

Syntax:

if condition1
then
    # code for condition1 being true
elif condition2
then
    # code for condition2 being true
else
    # code for all conditions being false
fi

This allows you to check multiple conditions in sequence. The first condition that evaluates to true will execute its corresponding block of code. If none are true, the else block will execute.

Share
OpenLib .

OpenLib .

The Founder - OpenLib.io

You may also like...