Bash Scripting - If Statement
Last Updated :
22 Dec, 2023
Bash is an interpreter for command languages. It is a default command interpreter on most GNU/Linux systems and is widely available on various operating systems. The name is an abbreviation for Bourne-Again SHell. Scripting enables for the execution of instructions that would otherwise be executed one by one interactively.
In this article, we will discuss about if statement in bash scripting.
Bash If Statement
The basic syntax of an `if` statement in Bash:
#!/bin/bash
if [ condition ]; then
# code to be executed if the condition is true
fi
Explanation:
if [ condition ]; then
: This line starts the if statement, where condition
is the expression that is evaluated. If the condition is true, the code inside the then
block is executed.# code to be executed if the condition is true
: This is the code block that is executed if the condition specified in the if statement is true.fi
: This marks the end of the if statement.
Bash Script to Determine if a Number is Even
The following is an example script that will prompt you to input a number and then it checks whether the given number is even.
#!/usr/bin/bash
# This script prompts the user to enter a number, checks if it's even, and prints a message accordingly.
# Prompt the user to enter a number
echo -n "Enter Number: "
read x
# Check if the entered number is even
if [ $((x % 2)) == 0 ]; then
echo "Number is Even"
fi
Explanation:
#!/usr/bin/bash
: This is a shebang line that specifies the path to the Bash interpreter. It indicates that the script should be executed using Bash.echo -n "Enter Number: "
: This line prints the prompt "Enter Number: " without a newline character (-n
option). It waits for the user to enter a number.read x
: Reads the user input and assigns it to the variable x
.if [ $((x % 2)) == 0 ]; then
: This line checks if the remainder of the division of the entered number (x
) by 2 is equal to 0. If true, it means the number is even.echo "Number is Even"
: If the condition in the if statement is true, this line prints "Number is Even" to the console.
Output:
Bash Script to Determine if a Number is EvenNote: The script does not handle cases where the user enters a non-numeric value. If the user enters a non-numeric value, it may produce unexpected results. Additional input validation could be added to address this.
Bash if-else Statement
The basic syntax of an `if-else` statement in Bash:
#!/bin/bash
if [ condition ]; then
# code to be executed if the condition is true
else
# code to be executed if the condition is false
fi
Explanation:
if [ condition ]; then
: This line starts the if statement, where condition
is the expression that is evaluated. If the condition is true, the code inside the then
block is executed.# code to be executed if the condition is true
: This is the code block that is executed if the condition specified in the if statement is true.else
: If the condition in the if statement is false, the code inside the else
block is executed.# code to be executed if the condition is false
: This is the code block that is executed if the condition specified in the if statement is false.fi
: This marks the end of the if-else statement.
How to Find The Greater Number Using if-else Statements in Bash Script?
Here is the Bash script to find out the greater number using if-else statement in Bash Script.
#!/bin/bash
# Prompt the user to enter a value for x
echo -n "Enter the value of x: "
read x
if [ $x -gt 5 ]; then
echo "x is greater than 5"
else
echo "x is not greater than 5"
fi
Explantation:
- #!/bin/bash: This line is called a shebang and indicates that the script should be interpreted and executed using the Bash shell.
- # Prompt the user to enter a value for x: This is a comment indicating the purpose of the next line.
- echo -n "Enter the value of x: ": This line prints the message "Enter the value of x: " to the terminal without moving to the next line. The user will input their value on the same line.
- read x: This line reads the user's input and assigns it to the variable 'x'.
- if [ $x -gt 5 ]; then: This is an if statement that checks whether the value of 'x' is greater than 5.
- $x: Represents the value of the variable 'x'.
- -gt: Stands for "greater than" in the context of numerical comparison.
- 5: The value being compared against.
- echo "x is greater than 5": If the condition in the previous line is true, this line will be executed, printing "x is greater than 5" to the terminal.
- else: If the condition in the if statement is false, the script jumps to the else block.
- echo "x is not greater than 5": This line is executed if the value of 'x' is not greater than 5, printing "x is not greater than 5" to the terminal.
- fi: This signifies the end of the if-else block.
Output:
Finding greater number using if-else Bash if-elif-else Statement
The if-elif-else
statement in Bash is used for conditional branching. It allows you to specify multiple conditions and execute different blocks of code based on the evaluation of these conditions.
The basic syntax of an `if-elif-else` statement in Bash:
#!/bin/bash
if [ condition1 ]; then
# Code to be executed if condition1 is true
elif [ condition2 ]; then
# Code to be executed if condition2 is true
elif [ condition3 ]; then
# Code to be executed if condition3 is true
else
# Code to be executed if none of the conditions are true
fi
Explanation:
- if [ condition1 ]; then: This is the starting point of the
if-elif-else
statement. The code within this block will be executed if condition1
is true. - # Code to be executed if condition1 is true: Replace this comment with the actual code you want to run if
condition1
is true. - elif [ condition2 ]; then: If
condition1
is false, the script checks condition2
. If condition2
is true, the code within this block is executed. - # Code to be executed if condition2 is true: Replace this comment with the actual code you want to run if
condition2
is true. - elif [ condition3 ]; then: If both
condition1
and condition2
are false, the script checks condition3
. If condition3
is true, the code within this block is executed. - # Code to be executed if condition3 is true: Replace this comment with the actual code you want to run if
condition3
is true. - else: If none of the preceding conditions (condition1, condition2, condition3, etc.) is true, the code within the
else
block is executed. - # Code to be executed if none of the conditions are true: Replace this comment with the actual code you want to run if none of the conditions are true.
- fi: This marks the end of the
if-elif-else
statement. The word "fi" is "if" spelled backward and is used to close the conditional blocks in Bash.
How to Find if Number is Positive, Negative or Zero Using `if-elif-else` Statement in Bash?
Let's augment the code in the above example to add the condition to check for zero.
#!/bin/bash
# Prompt the user to enter a number
echo -n "Enter a number: "
read num
if [ $num -gt 0 ]; then
echo "$num is a positive number."
elif [ $num -lt 0 ]; then
echo "$num is a negative number."
else
echo "$num is zero."
fi
Explanation:
- #!/bin/bash: This line is a shebang indicating that the script should be interpreted and executed using the Bash shell.
- # Prompt the user to enter a number: This is a comment indicating the purpose of the next line.
- echo -n "Enter a number: ": This line prints the message "Enter a number: " to the terminal without moving to the next line. The user will input their number on the same line.
- read num: This line reads the user's input and assigns it to the variable 'num'.
- if [ $num -gt 0 ]; then: This is an if statement that checks whether the value of 'num' is greater than 0.
- $num: Represents the value of the variable 'num'.
- -gt: Stands for "greater than" in the context of numerical comparison.
- 0: The value being compared against.
- echo "$num is a positive number.": If the condition in the previous line is true, this line will be executed, printing "$num is a positive number." to the terminal.
- elif [ $num -lt 0 ]; then: If the condition in the if statement is false, this line checks whether the value of 'num' is less than 0.
- $num: Represents the value of the variable 'num'.
- -lt: Stands for "less than" in the context of numerical comparison.
- 0: The value being compared against.
- echo "$num is a negative number.": If the condition in the elif statement is true, this line will be executed, printing "$num is a negative number." to the terminal.
- else: If both the conditions in the if and elif statements are false, the script jumps to the else block.
- echo "$num is zero.": This line is executed if the value of 'num' is not greater than 0 and not less than 0, printing "$num is zero." to the terminal.
- fi: This signifies the end of the if-elif-else block.
Output:
if Number is Positive, Negative or Zero Using `if-elif-else`
Bash Nested if Statement
In Bash, you can use nested if
statements to create more complex conditional structures. Here's the syntax for a nested if
statement:
#!/bin/bash
if [ condition1 ]; then
# Code to be executed if condition1 is true
if [ condition2 ]; then
# Code to be executed if condition2 is true
else
# Code to be executed if condition2 is false
fi
else
# Code to be executed if condition1 is false
fi
Explanation:
- if [ condition1 ]; then: This is the outer
if
statement. If condition1
is true, the code inside this block is executed. - # Code to be executed if condition1 is true: Replace this comment with the actual code you want to run if
condition1
is true. - if [ condition2 ]; then: Inside the block of the outer
if
statement, there is an inner if
statement. If condition2
is true, the code inside this block is executed. - # Code to be executed if condition2 is true: Replace this comment with the actual code you want to run if
condition2
is true. - else: If
condition2
in the inner if
statement is false, the code inside the else
block of the inner if
statement is executed. - # Code to be executed if condition2 is false: Replace this comment with the actual code you want to run if
condition2
is false. - fi: This marks the end of the inner
if
statement. - else: If
condition1
in the outer if
statement is false, the code inside the else
block of the outer if
statement is executed. - # Code to be executed if condition1 is false: Replace this comment with the actual code you want to run if
condition1
is false. - fi: This marks the end of the outer
if
statement.
How to Check Age Eligibility and Senior Citizen Benefits in Bash Using Nested If Statements?
Let's tweak the code above a little bit to use nested-if.
#!/bin/bash
# Prompt the user to enter an age
echo -n "Enter your age: "
read age
if [ $age -ge 18 ]; then
echo "You are eligible to vote."
if [ $age -ge 65 ]; then
echo "You are also eligible for senior citizen benefits."
else
echo "You are not yet eligible for senior citizen benefits."
fi
else
echo "You are not eligible to vote yet."
fi
Explanation:
- #!/bin/bash: This line is a shebang indicating that the script should be interpreted and executed using the Bash shell.
- # Prompt the user to enter an age: This is a comment indicating the purpose of the next line.
- echo -n "Enter your age: ": This line prints the message "Enter your age: " to the terminal without moving to the next line. The user will input their age on the same line.
- read age: This line reads the user's input and assigns it to the variable 'age'.
- if [ $age -ge 18 ]; then: This is an if statement that checks whether the value of 'age' is greater than or equal to 18.
- $age: Represents the value of the variable 'age'.
- -ge: Stands for "greater than or equal to" in the context of numerical comparison.
- 18: The value being compared against.
- echo "You are eligible to vote.": If the condition in the previous line is true, this line will be executed, printing "You are eligible to vote." to the terminal.
- if [ $age -ge 65 ]; then: Inside the first if block, this is another if statement that checks whether the value of 'age' is greater than or equal to 65.
- $age: Represents the value of the variable 'age'.
- -ge: Stands for "greater than or equal to" in the context of numerical comparison.
- 65: The value being compared against.
- echo "You are also eligible for senior citizen benefits.": If the condition in the inner if statement is true, this line will be executed, printing "You are also eligible for senior citizen benefits." to the terminal.
- else: If the condition in the inner if statement is false, the script jumps to the else block inside the outer if statement.
- echo "You are not yet eligible for senior citizen benefits.": This line is executed if the value of 'age' is not greater than or equal to 65, printing "You are not yet eligible for senior citizen benefits." to the terminal.
- fi: This signifies the end of the inner if-else block.
- else: If the condition in the outer if statement is false, the script jumps to the else block.
- echo "You are not eligible to vote yet.": This line is executed if the value of 'age' is not greater than or equal to 18, printing "You are not eligible to vote yet." to the terminal.
- fi: This signifies the end of the outer if-else block.
Output:
nested-if using Bash
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
What is Vacuum Circuit Breaker? A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac
13 min read
Linux Commands Cheat Sheet Linux, often associated with being a complex operating system primarily used by developers, may not necessarily fit that description entirely. While it can initially appear challenging for beginners, once you immerse yourself in the Linux world, you may find it difficult to return to your previous W
13 min read
AVL Tree Data Structure An AVL tree defined as a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees for any node cannot be more than one. The absolute difference between the heights of the left subtree and the right subtree for any node is known as the balance factor of
4 min read