Facebook Twitter Instagram
    TecAdmin
    • Home
    • FeedBack
    • Submit Article
    • About Us
    Facebook Twitter Instagram
    TecAdmin
    You are at:Home»Bash Tips & Tricks»How to Use Logical OR & AND in Shell Script with Examples

    How to Use Logical OR & AND in Shell Script with Examples

    By RahulApril 18, 20234 Mins Read

    Logical operators are used to combine multiple conditions in a script, allowing for more complex decision-making. The two most commonly used logical operators in shell scripting are Logical OR (||) and Logical AND (&&).

    Advertisement

    These operators are used in conditional statements like if, while, and until, as well as in command chaining. Command chaining is a technique where multiple commands are executed in a sequence, based on the success or failure of previous commands.

    • The Logical OR operator (||) is used to execute the command following it only if the previous command fails (returns a non-zero exit status).
    • The Logical AND operator (&&) is used to execute the command following it only if the previous command is successful (returns a zero exit status).

    1. Using Logical OR (||) in Shell Scripts

    Logical OR in bash script is used with operator -o. Write a small shell script that will show how to use logical OR ( || ) operator between two conditions.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    #!/bin/bash
     
    read -p "Enter First Numeric Value: " first
    read -p "Enter Second Numeric Value: " second
     
    if [ $first -le 10 ] || [ $second -gt 20 ]
    then
        echo "At least one conditions is true"
    else
        echo "Both conditions are failed"
    fi

    This shell script prompts the user to input two numeric values. It then checks if either the first value is less than or equal to 10, or the second value is greater than 20. If at least one of these conditions is met, the script outputs “At least one condition is true.” Otherwise, it outputs “Both conditions are failed.”

    2. Using Logical AND (&&) in Shell Scripts

    Logical AND in bash script is used with operator -a. Below shell script will show you to how to use logical AND ( && ) between two conditions.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    #!/bin/bash
     
    read -p "Enter First Numeric Value: "  first
    read -p "Enter Second Numeric Value: "  second
     
    if [ $first -le 10 ]  && [ $second -gt 20 ]
    then
        echo "Both conditions are true"
    else
        echo "Atleast one conditions is false"
    fi

    This shell script prompts the user to input two numeric values. It then checks if the first value is less than or equal to 10 and the second value is greater than 20. If both conditions are met, the script outputs “Both conditions are true.” Otherwise, it outputs “At least one condition is false.”

    3. Using Multiple Logical OR & AND

    Now, use the multiple logical operators in a single statement. The below example will help you to understand how to use multiple logical operators in a single statement.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    #!/bin/bash
     
    # A sample shell script to take input a number from the user
    # Check if the number is between 10 - 20
    # Or number is between 100 - 200
     
    read -p "Enter a number: " num
     
    if ([ $num -ge 10 ] && [ $num -le 20 ]) || ([ $num -ge 100 ] && [ $num -le 200 ])
    then
         echo "Input number ($num) is between 10-20 or 100-200"
    else
         echo "Input number ($num) is neither between 10-20 nor 100-200"
    fi

    This shell script allows a user to input a number and then checks if the entered number lies within either the range of 10-20 or 100-200. The script then outputs a message to the user indicating whether the input number falls within one of these specified ranges or not.

    4. A Practical Example

    In this practical example, we’ll create a shell script that checks if a server is reachable and if a specific directory exists on the local machine. If both conditions are met, the script will create a backup of the directory and transfer it to the remote server using scp. If any of these conditions are not met, it will print an appropriate error message.

    Create a file called backup_and_transfer.sh and add the following content:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    #!/bin/bash
     
    # Configuration
    HOST="example.com"
    DIRECTORY="/path/to/directory"
    BACKUP_FILE="backup_$(date +%Y%m%d).tar.gz"
    REMOTE_PATH="/remote/backup/directory"
     
    # Check if the host is reachable and the local directory exists
    ping -c 1 "$HOST" > /dev/null && [ -d "$DIRECTORY" ] && {
     
        # Create a backup of the directory
        tar -czf "$BACKUP_FILE" "$DIRECTORY" && {
     
            # Transfer the backup file to the remote server
            scp "$BACKUP_FILE" "$HOST":"$REMOTE_PATH" && {
                echo "Backup and transfer completed successfully."
                exit 0
            } || {
                echo "Failed to transfer the backup file."
                exit 1
            }
     
        } || {
            echo "Failed to create the backup file."
            exit 1
        }
     
    } || {
        echo "Host is not reachable or the local directory does not exist."
        exit 1
    }

    This script demonstrates the use of Logical AND (&&) and Logical OR (||) operators to chain commands, create backup files, and transfer them to a remote server, while handling errors and providing useful feedback.

    Conclusion

    Mastering the Logical OR (||) and Logical AND (&&) operators in shell scripting enables you to create efficient and effective scripts for managing systems and automating tasks. By understanding their usage and combining them as needed, you can create complex decision trees and streamline your shell scripts. Remember to follow best practices, such as using parentheses to group conditions and leveraging short-circuit evaluation, to optimize your scripts and ensure they work as intended. With practice and a thorough understanding of these logical operators, you’ll be well on your way to becoming a shell scripting expert.

    bash Operator shell script
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email WhatsApp

    Related Posts

    Handling Special Characters in Shell Scripts

    What are the difference between SH and BASH

    What are the difference between SH and BASH?

    Bash Convert String Lowercase (4 Methods)

    View 5 Comments

    5 Comments

    1. Two D Man on November 13, 2022 2:48 am

      Even though there is a “modern approach” some of us might be trying to read old scripts. There are plenty of scripts out there that use -o and -a. Do you think, suddenly, they will all stop working?

      Reply
    2. Mark on July 23, 2021 2:48 am

      Using “-o” and “-a” is deprecated. The modern approach is “||” and “&&” with enclosing brackets [].

      Also, your example for using multiple and/or in bash does not work and gets a syntax error (you can’t use parenthesis like that inside brackets; did you test it?). You CAN uses parenthesis if using “||” or “&&” outside of brackets.

      Reply
      • Rahul on July 23, 2021 5:43 am

        Hi Mark, I have updated the tutorial with a modern approach.

        Thank you for your valuable suggestions.

        Reply
    3. Corona Xiomara on September 23, 2019 6:05 pm

      Thank you so much! I was so lost, could not find this anywhere. 🙂

      Reply
    4. Vinod Kumar Gupta on September 4, 2019 9:34 am

      Thank You. 🙂

      Reply

    Leave A Reply Cancel Reply

    Advertisement
    Recent Posts
    • A Comprehensive Look at the Simple Mail Transfer Protocol (SMTP)
    • Understanding Basic Git Workflow: Add, Commit, Push
    • The Difference Between Git Reset –soft, –mixed, and –hard
    • Understanding the Staging Area in Git’s Workflow
    • Python Function with Parameters, Return and Data Types
    Facebook Twitter Instagram Pinterest
    © 2023 Tecadmin.net. All Rights Reserved | Terms  | Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.