Conditional Statements in Bash | Bash Conditional Statement

In this blog, we will learn about the Conditional Statement in Bash Scripting. We will see what different types of Conditional Statements are present in Bash Scripting. We will see all the Conditional statements in the program. So let’s get started with the blog.

Introduction to Conditional Statements in Bash Scripting

Conditional statements in Bash scripting allow you to execute different code blocks based on specific conditions. They help us decide whether or not to run a piece of code based on the conditions that we may set.

Let’s see the structure of the Conditional Statement in Bash Scripting:

if [ condition ]; then
    # code to execute if the condition is true
elif [ another_condition ]; then
    # code to execute if another condition is true (optional)
else
    # code to execute if all conditions are false (optional)
fi

Here’s a breakdown of the elements:

  • "if initiates the conditional block.
  • "[condition]" is the test condition enclosed in square brackets. Common conditions involve comparisons, file checks, or arithmetic evaluations.
  • then" signifies the start of the code block to execute if the condition is true.
  • "elif (optional)” allows for testing additional conditions.
  • "else (optional)” defines the code block to execute if no previous conditions are true.
  • "fi marks the end of the conditional block.

Types of Conditional Statements in Bash Scripting

A) Basic IF statement

In Bash scripting, the “if” statement allows you to conditionally execute a block of code based on a specific condition. If a particular condition is true, then it only executes that set of actions. If it does not satisfy the condition, then it will not execute that set of statements.

Syntax:

if condition; then
    # Code to execute if the condition is true
fi

Note: The statement between the then” and “if” statements will execute if and only if the condition is true.

Note: Observe the spaces used in the first line and a semicolon at the end of the first line; both are mandatory to use. If the conditional statement ends with fi.

Let’s see an example of a Bash IF Statement:

Program 1: Comparison between two numbers

                                                                                                                                                                                                   #!/bin/bash

num1=23
num2=25

if [[ $num2 -gt $num1 ]]
then
        echo "$num2 is greater than $num1"
fi


Output:
25 is greater than 23

Here, you can see the condition or expression of the “if” statement is satisfied, therefore it executed the “then” block of the program.

Note: How to run a bash script.

Suppose your file name is “demo.sh”

Step 1: Change the permission of the file by using the command.

sudo chmod u+x demo.sh

Step 2: Now run the file

./demo.sh

Program 2: Check whether the file exists or not.


#!/bin/bash
 
if [ -f /home/kali/Downloads/Bash/Conditional_Statement/compare_number.sh ]
then
        echo "File exists"
fi


Output:
File exists 

Here, the “-f” option is used to check whether a provided file exists or not.

B) Nested IF Statement

A nested if statement in Bash allows you to have one if statement inside another. This is useful when you need to evaluate multiple conditions sequentially.

Syntax:

if condition1; then
    # Code to execute if condition1 is true

    if condition2; then
        # Code to execute if condition2 is true
    else
        # Code to execute if condition2 is false
    fi

else
    # Code to execute if condition1 is false
fi

Let us see a simple nested if statement:

Program: Check whether the person is an adult or not. If not, then it should not be allowed to be drunk.

#!/bin/bash

age=18

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

    if [ "$age" -ge 21 ]; then
        echo "You are old enough to drink."
    else
        echo "You are not old enough to drink."
    fi

else
    echo "You are a minor."
fi

Output:
You are an adult
You are not old enough to drink

In this example, there is a nested if statement inside the initial if block. It first checks if the age is greater than or equal to 18. If true, it then checks if the age is also greater than or equal to 21, and accordingly outputs messages.

You can continue nesting if statements to handle more complex conditions and actions based on those conditions. Just make sure to maintain the proper indentation and structure to ensure clarity and readability.

C) IF-ELSE Statement

In Bash scripting, the “if-else" statement allows you to execute different code blocks based on a specific condition. The basic syntax for the “if-else" a statement is as follows:

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

Here’s a breakdown of the elements:

  • "if initiates the conditional block.
  • "condition" is the expression or command that evaluates to true or false.
  • "then signifies the start of the code block to execute if the condition is true.
  • "else" defines the code block to execute if the condition is false (optional).
  • "fi marks the end of the conditional block.

Program: Comparison between two strings

#!/bin/bash
name="binfintech"

if [ "$name" == "binfintech" ]
then
        echo "String is equal"
else
        echo "String is not equal"
fi

Output:
String is equal

From the above code, we can conclude that the program executes based on the condition. Here “name” is equal to “binfintech, which is why it executes the then block statement.

D) ELSE-IF Statement

In Bash scripting, the elif (short for “else if”) statement allows you to evaluate multiple conditions sequentially. It follows an initial if" statement and comes before the "else” statement. The syntax for the “elif statement” is as follows:

if condition1; then
    # code to execute if condition1 is true
elif condition2; then
    # code to execute if condition2 is true
elif condition3; then
    # code to execute if condition3 is true
else
    # code to execute if all conditions are false
fi

Here’s a breakdown of the elements:

  • "elif allows for testing additional conditions.
  • "condition2“, condition3, and so on represent additional conditions to evaluate.
  • "then" signifies the start of the code block to execute if the respective condition is true.
  • The "elif" statements can be followed by additional "elif statements as needed.
  • "else (optional)” defines the code block to execute if all previous conditions are false.
  • "fi marks the end of the conditional block.

Program: Check whether the the person can drink or not.

#!/bin/bash

age=25

if [ "$age" -lt 18 ]; then
    echo "You are a minor."
elif [ "$age" -ge 18 ] && [ "$age" -lt 21 ]; then
    echo "You are an adult but not old enough to drink."
elif [ "$age" -ge 21 ]; then
    echo "You are old enough to drink."
else
    echo "Invalid age."
fi

Output:
You are old enough to drink.

In this example, the script evaluates multiple conditions using theelif" statement and executes the corresponding code block based on the condition that is true. The "else clause (optional) defines what to do if all conditions are false.

E) CASE Statement

The "case" statement in Bash scripting allows you to easily handle multiple conditions based on the value of a variable or expression. It simplifies the structure and readability of your script when dealing with several possible options.

Syntax:

case expression in
    pattern1)
        # code to execute if expression matches pattern1
        ;;
    pattern2)
        # code to execute if expression matches pattern2
        ;;
    pattern3)
        # code to execute if expression matches pattern3
        ;;
    *)
        # code to execute if no patterns match
        ;;
esac

Here’s a detailed explanation:

  • case initiates the case statement.
  • "expression" is the variable or expression being evaluated.
  • "in marks the start of the patterns to match against.
  • pattern1, pattern2, etc”., are the patterns to match against the expression.
  • ") indicates the end of a pattern.
  • ";;" is used to separate each pattern and the code to execute if a pattern matches.
  • "*) is the default case and is executed if none of the patterns match.

Program: Choose a fruit

#!/bin/bash

fruit="kiwi"

case $fruit in
        "apple")
                echo "You choose an apple"
        ;;
        
        "orange")
                echo "You choose an orange"
        ;;
        "kiwi")
                echo "You choose a kiwi"
        ;;
        *)
        echo "Unkown Fruit"
esac

Output:
You choose a kiwi

In this example, the script prompts the user to enter a fruit, and then the case statement checks the input against different fruit patterns. Depending on the input, it executes the corresponding code block. If the input doesn’t match any patterns, the default case (*) is executed.

Note: The blog is mainly referenced from Javatpoint of Bash Learning.

FAQ of Conditional Statements in Bash

What is a conditional statements in Bash Scripting?

Conditional statements in Bash scripting allow you to execute different code blocks based on specific conditions. They help us decide whether or not to run a piece of code based on the conditions that we may set.

What are the different types of Conditional Statements in Bash Scripting?

The different types of conditional statements are as follows:
1) IF Statement
2) IF-ELSE Statement
3) ELSE-IF Statement
4) CASE Statement

Recent Articles on Linux Operating System

  1. Directory in Linux Define | Linux Directory & its Commands
  2. Explain the chmod command in Linux | Linux chmod command
  3. Linux User Management || User Management in Linux
  4. Linux Computer Network Advanced Command | Network Command
  5. Redirection in Linux I/O| Linux I/O Redirection
  6. CronTab and Job Scheduling in Linux | Make CronTab Project
  7. Linux Firewall Unlock Rules with Firewall-cmd Tutorial
  8. netstat command in Linux | Linux netstat command
  9. SSH Command Full Guide with Practical | Linux SSH Service
  10. awk command Guide | How to arrange the output of the file in Linux
  11. sed command Full Guide Tutorial | Linux sed Command
  12. Iptables commands Full Guide: How to make our own Firewall

Recent Articles on Computer Networks

  1. Introduction to Computer Networking | What is Computer Network
  2. What are Topology & Types of Topology in Computer Network
  3. What is FootPrinting in Cyber Security and its Types, Purpose
  4. Introduction to Cloud Computing | What is Cloud Computing
  5. Distributed Shared Memory and Its Advantages and Disadvantages
  6. What is a VPN? How does a VPN Work? What VPN should I use?
  7. What is an Internet and How the Internet Works
  8. What is a Website and How Does a Website or web work?
  9. Introduction to Virus and Different Types of Viruses in Computer
  10. What is TCP and its Types and What is TCP three-way Handshake
  11. What is the UDP Protocol? How does it work and what are its advantages?
  12. What is an IP and its Functions, What is IPv4 and IPv6 Address
  13. What is MAC Address and its Types and Difference MAC vs IP
  14. What is ARP and its Types? How Does it Work and ARP Format
  15. Sessions and Cookies and the Difference Between Them
  16. What is ICMP Protocol and its Message Format?
  17. What is Big Data? Characteristics and Types of Big Data
  18. Disciplines of CyberSecurity | What are the goals of CyberSecurity?
  19. What is Firewall, Features, Types and How does the Firewall Work?
  20. Network Scanning, Types, and Stealth Scan in Computer Network
  21. Cryptography and its Types in Ethical Hacking
  22. Tor Browser and How Does It Work | Onion Router Tutorial
  23. Proxy Server, Advantages, Difference between Proxy Server & VPN
  24. DHCP Protocol and What Are the Pros and Cons of DHCP
  25. Intrusion Detection System(IDS) and What are the types of IDS
  26. Domain Name Server, How Does It Work, and its advantages
  27. Telnet: Introduction, How Does it Work, and Its Pros and Cons
  28. SOC: Introduction, Functions performed by SOC, and its Pros
  29. What is SIEM? | What is the Difference between SIEM and SOC?
  30. Application Layer in OSI Model | OSI Model Application Layer
  31. What is SSL Protocol or SSL/TLS and SSL Handshake, and Architecture of SSL
  32. What are Servers, how do they work, and its different Types
  33. Network Devices-Router, Switch, Hub, etc in Computer Network
  34. Connection Oriented and Connection-less Services in Network
  35. Physical Layer in OSI Model | OSI Model Physical Layer
  36. Presentation Layer in OSI Model | OSI Model Presentation Layer
  37. Session layer in OSI Model | OSI Model Session layer
  38. Transport Layer in OSI Model | Computer Network Transport Layer
  39. Network Layer in OSI Model | OSI Model Network Layer
  40. Data Link Layer in OSI Model | OSI Model Data Link Layer
  41. Block Diagram of Communication System with Detailed Explanation

By Vivek Maurya

Write blogs related to Ethical hacking, Computer networks, Linux, Penetration testing and Web3 Security.

Leave a Reply

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