Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Bash scripting if Statement With Examples

Last Updated on July 5, 2023 by Mayank Dham

Bash, short for "Bourne Again SHell," is a powerful scripting language used in Unix-based operating systems. One of the fundamental constructs in Bash programming is the if statement. The if statement allows you to control the flow of your script based on specific conditions. In this article, we will delve into the intricacies of Bash if statements, exploring their syntax, various conditionals, and examples to illustrate their usage.

Basic If statements

A basic if statement commands that if a particular condition is true, then only execute a given set of actions. If it is not true, then do not execute those actions. If statement is based on the following format:

Syntax of If statement
if condition
then

Code block executed when condition is true

else
    # Code block executed when condition is false
fi

Conditions of using if statement

Bash provides several conditionals that you can use within if statements:
1. Numeric Comparisons:

  • -eq: Equal to
  • -ne: Not equal to
  • -gt: Greater than
  • -lt: Less than
  • -ge: Greater than or equal to
  • -le: Less than or equal to

2. String Comparisons:

  • ==: Equal to
  • !=: Not equal to
  • -z: Empty string
  • -n: Non-empty string

3. File and Directory Checks:

  • -e: Exists
  • -f: Regular file
  • -d: Directory
  • -r: Readable
  • -w: Writable
  • -x: Executable

Example of using If Statement:

Let’s illustrate the usage of if statements with a few examples:

Example 1: Numeric Comparison

!/bin/bash

count=10

if [ $count -gt 0 ]
then
    echo "Count is positive."
else
    echo "Count is zero or negative."
fi

Example 2: String Comparison

!/bin/bash

name="Alice"

if [ "$name" == "Alice" ]
then
    echo "Hello, Alice!"
else
    echo "You are not Alice."
fi

Example 3: File Check

    #!/bin/bash

file_path="/path/to/file.txt"

if [ -f "$file_path" ]
then
    echo "File exists."
else
    echo "File does not exist."
fi

Compound Condition
You can combine multiple conditions using logical operators like && (AND) and || (OR). Here’s an example:

!/bin/bash

age=25
grade="A"

if [ $age -gt 18 ] && [ "$grade" == "A" ]
then
    echo "Congratulations! You are eligible for a scholarship."
else
    echo "Sorry, you are not eligible for a scholarship."
fi

Nested If statement
In your bash script, you have the flexibility to incorporate multiple if statements as needed. Furthermore, it is entirely possible to nest an if statement within another if statement, creating what is referred to as a nested if statement.

Syntax of nested if statement
if condition1
then

Code block executed when condition1 is true

    if condition2
    then
        # Code block executed when both condition1 and condition2 are true
    else
        # Code block executed when condition1 is true, but condition2 is false
    fi

else
    # Code block executed when condition1 is false
fi

Example of Nested if statement

Let’s explore an example to demonstrate the application of nested if statements:

#!/bin/bash

num=10

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

    if (( num % 2 == 0 ))
    then
        echo "The number is even."
    else
        echo "The number is odd."
    fi

else
    echo "The number is not positive."
fi

Conclusion
The Bash if statement is a fundamental construct that allows you to control the flow of your scripts based on specific conditions. By leveraging conditionals, such as numeric and string comparisons, and file and directory checks, you can create dynamic and responsive scripts. Additionally, nesting if statements provide even greater flexibility and precision in your conditional logic. Mastering the Bash if statement is essential for effective scripting in Unix-based operating systems. By understanding its syntax, conditionals, and examples, you can create robust scripts that adapt to different scenarios and make your automation tasks more efficient.

FAQs (Frequently Asked Questions) related to Bash if statements:

Q1. Can I have multiple conditions in a single if statement?
A1. Yes, you can combine multiple conditions using logical operators such as && (AND) and || (OR) to create compound conditions within a single if statement.

Q2. Can I use the if statement to check the existence of a file or directory?
A2. Absolutely. Bash provides conditionals like -e, -f, and -d to check the existence of a file or directory, along with other conditionals to check for readability, writability, and executability.

Q3. Can I nest if statements to multiple levels?
A3. Yes, you can nest if statements to multiple levels, but it is recommended to maintain code readability and avoid excessive nesting, which can make the code harder to understand.

Q4. Can I have an else statement without an if statement?
A4. No, an else statement must always be associated with an if statement. It provides the code block to be executed when the if condition evaluates to false.

Q5. Can I use variables in if statements?
A5. Yes, you can use variables in if statements. Just make sure to properly quote and handle any special characters or spaces in the variable values.

Q6. Can I use arithmetic comparisons in if statements?
A6. Yes, you can use arithmetic comparisons by enclosing the expressions within double parentheses ((…)) or using the -eq, -ne, -gt, -lt, -ge, and -le operators.

Leave a Reply

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