Open In App

Bash Scripting – If Statement

Improve
Improve
Like Article
Like
Save
Share
Report

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:

  1. #!/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.
  2. 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.
  3. read x: Reads the user input and assigns it to the variable x.
  4. 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.
  5. 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 Even

Bash Script to Determine if a Number is Even

Note: 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

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`

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

nested-if using Bash

FAQs and Some Notes on CONDITION

These are a few things to keep in my mind while writing test conditions in bash.

1. Ensure whitespaces between the brackets and the actual check/comparison statement.

For example, the following will not work.

if [$x==0]

Bash will report an error about a missing ].

2. Always end the line before adding a new keyword, such as “then.”

If, then, else, elif, and fi are all shell keywords, which means they can’t be used on the same line. Put a “;” between the previous statement and the keyword, or start a new line with the keyword.

3. To use many conditions in one statement, use logical operators.

We can use logical AND(&&) or logical OR(||) operators to use multiple conditions.

For example:

if [[ $x -ge $y ]] && [[ $x -ge $z ]]; then
echo "x is greatest"
fi

Here, -ge is a shorthand for greater than or equal to

4. How to compare strings in a Bash if statement?

Use the `=` operator for string equality and `!=` for inequality.

For example:

if [ "$string1" = "$string2" ]; then
# Code to execute if strings are equal
else
# Code to execute if strings are not equal
fi

5. Can I use regular expressions in Bash if statements?

Yes, you can use the `[[ ... ]]` construct for more advanced string matching with regular expressions.

For example:

if [[ "$string" =~ ^[0-9]+$ ]]; then
# Code to execute if the string contains only numbers
else
# Code to execute if the string does not contain only numbers
fi

6. How to check if a file exists in a Bash script using an if statement?

You can use the `-e` flag in the condition, like this:

if [ -e "filename" ]; then
# Code to execute if the file exists
else
# Code to execute if the file does not exist
fi

7. What is the syntax for an if-else statement in Bash scripting?

The basic syntax for an `if-else` statement in Bash scripting is:

if [ condition ]; then
# Code to execute if condition is true
else
# Code to execute if condition is false
fi

8. How do I use the elif statement in a Bash script?

The `elif` statement is used to check additional conditions if the initial if condition is false.

Here’s an example:

if [ condition1 ]; then
# Code to execute if condition1 is true
elif [ condition2 ]; then
# Code to execute if condition2 is true
else
# Code to execute if none of the conditions are true
fi

9. How can I use logical operators (AND, OR) in Bash if statements?

You can use `-a` for logical AND and `-o` for logical OR.

For example:

if [ condition1 -a condition2 ]; then
# Code to execute if both conditions are true
fi

Conclusion

In this article we discussed Bash scripting which is like a super useful tool for making your computer do things automatically. This article taught us about the “if” statement in Bash, which is like a decision-maker in scripts. We learned the basics, saw examples like checking if a number is even or figuring out if someone can vote, and even explored fancier stuff like handling many conditions or putting “if” statements inside each other. The article gave clear explanations, examples, and answered common questions to help us get better at using Bash scripts. The key takeaway is to be careful with details like spacing and special rules, so our scripts work smoothly and make tasks easier to handle on the computer.



Last Updated : 22 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads