Open In App

Bash Scripting – If Statement

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:

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

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:

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:

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:

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:

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:

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:

Output:

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.


Article Tags :