How to Use Bitwise “OR” Operator in Bash? [3 Different Cases]

LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now

In Bash, the bitwise OR (|) operator is used to perform OR operations on corresponding binary digits of integers. It works at a binary level, which means that it can be used to manipulate individual bits within numbers. To use the bitwise OR operator, you can assign the integer value to a variable and then employ the bitwise OR operator to the variable. Alternatively, you can directly use the value with the operator.

In this article, you will get the basic syntax and some cases where you can employ bitwise the OR operator. So let’s start!

Syntax of Bitwise “OR” Operator

The basic syntax of the bitwise OR operator (|) in Bash is as follows:

result=$((operand1 | operand2))

In this syntax, operand1 and operand2 are the values or expressions on either side of the bitwise OR operator. The double parentheses ((…)) are used for arithmetic evaluation in Bash.  For example, the bitwise OR operation between 5 and 3 is:

#!/bash/bin

# Perform bitwise OR operation and assign the result directly
result=$((5 | 3))

# Display the result
echo "The result is $result"

It is possible to use variable substitution with bitwise bash operators. Therefore, you can assign the value first and then apply the bitwise OR operator.

#!/bash/bin

 #Assign the value to the variable
var1=5
var2=3

# Perform bitwise OR operation between variables.
result=$((var1 | var2))

# Display the result
echo "The result is $result"

Here, both codes are correct and produce an output of 7.

3 Practical Cases to Use Bitwise “OR” Operator in Bash Script

In the upcoming section of this article, you will find three different scenarios that demonstrate the use of the bitwise OR operator. These scenarios include implementing the operator in an arithmetic expansion, in a function, and in a loop. Let’s explore these cases.

Case 1: Bitwise “OR (|)” Operator in Arithmetic Expansion

In arithmetic expansion, you can use the single pipe | for bitwise OR operations. Here’s an example:

#!/bin/bash
# Prompt the user to enter two numbers
read -p "Enter the first number: " num1
read -p "Enter the second number: " num2

# Perform bitwise OR operation using arithmetic expansion
result=$((num1 | num2))

# Display the result
echo "The result of $num1 | $num2 is $result"
EXPLANATION

This Bash script prompts the user to enter two numbers, reads the input, and then performs a bitwise OR operation on the entered numbers using arithmetic expansion. The read command is used to take user input for the first and second numbers. The bitwise OR operation is executed with ((…)), and the result is stored in the result variable. Finally, the script displays the entered numbers and the result of the bitwise OR operation using the echo command.

Bitwise OR Operator in Arithmetic ExpansionAs you can see from the above image, the bitwise OR operation between 3 and 5 is 7. Here, the binary value of 3 is 011, and the binary value of 5 is 101. Now, performing the OR operation between these two binary values results in 111, which is equivalent to 7 in decimal notation.

Case 2: Bitwise “OR (|)” Operator in a Function

You can use bitwise operators within a Bash function to perform specific bit-level operations. Here’s an example of a function that uses the bitwise OR operator (|) to check if a particular bit is set:

#!/bin/bash

# Function to check if a specific bit is set using the OR operator
check_bit() {
    number=$1
    bit_position=$2

    # Use bitwise OR to check if the bit is set
    result=$((number | (1 << bit_position)))

    if [ $result -ne 0 ]; then
        echo "Bit at position $bit_position is set in $number."
    else
        echo "Bit at position $bit_position is not set in $number."
    fi
}

# Giving the arguments to the function
check_bit 10 2
EXPLANATION

The Bash code defines a function named check_bit that determines whether a specific bit is set in a given number. The function takes two parameters: number, the integer to be examined, and bit_position, the position of the bit to be checked. The function utilizes the bitwise OR operator (|) to perform a bitwise OR operation between the given number and a bitmask generated by left-shifting 1 to the specified bit position. The result is then evaluated, and if non-zero, the function asserts that the bit is set; otherwise, it declares that the bit is not set.

Bitwise OR Operator in a FunctionFor the given value of 10, the position in 2 is set, thus the bash code returns “Bit at position 2 is set in 10”.

Case 3: Bitwise “OR (|)” Operator in a Loop

Now, If you want to use the bitwise OR (|) operator within a loop, you can perform bitwise operations on a variable during each iteration. Here’s a sample example that demonstrates the idea of incorporating the for loop with the bitwise OR operator in Bash:

#!/bin/bash

# Initial value
result=0

# Bitwise OR operation in a loop
for (( i=1; i<=5; i++ )); do
    # Simulate some value to bitwise OR with the result
    value=$((i * 2))
    
    # Perform bitwise OR operation
    result=$((result | value))
    
    echo "Iteration $i: Result = $result"
done

echo "Final Result: $result"
EXPLANATION

The Bash script begins by initializing the variable result to 0. for (( i=1; i<=5; i++ )); do is a loop (from 1 to 5), where in each iteration, it simulates a value (value) by multiplying the loop index (i) by 2. The script performs a bitwise OR operation between the current result and the simulated value, updating the result accordingly. This process is repeated in each iteration, and the script prints the iteration number along with the updated result. Finally, after the loop, the script prints the final result, which represents the cumulative effect of the bitwise OR operations performed during the iterations.

Bitwise OR Operator in a LoopHere, the code iterates 5 times and returns the accumulated final result of 14 to the terminal.

Conclusion

Learning how to use the bitwise OR operator is one of the most useful bitwise operators in bash programming because it allows you to handle binary data more efficiently and flexibly. This article provides 3 different use cases where you can effectively incorporate the bitwise OR operator in the bash script. However, if you have any questions or queries related to this article, feel free to comment below. Thank you!

People Also Ask

What is the use of ‘Bitwise OR’?

The bitwise OR (|) operator in Bash is generally used for performing bitwise operations on integers. However, it can be used to set file access rights, script options, and other flags or permissions, and conditional statements to create complex conditions by mixing simpler ones, masking and filtering to selectively modify or extract specific bits within the binary representation.

What does || do in bash script?

In Bash scripting, the || (double pipe) operator is a logical operator used for conditional execution. It is known as the logical OR operator. Here’s how it works:

  1. It is used in command sequences to execute the next command only if the previous one fails.
    # Execute 'command1'; if it fails, then execute 'command2'
    command1 || command2
  2. It is often used for error handling or to ensure that a script proceeds with the next command only if the previous one fails.
    # Check if a file exists; if not, display an error message
    [ -e "myfile.txt" ] || echo "Error: File not found."

What is the difference between ‘Bitwise OR’ and ‘Bitwise Exclusive OR’?

The ‘Bitwise OR’ (|) and ‘Bitwise Exclusive OR’ (XOR or ^) are binary operators used for manipulating individual bits in binary numbers. The ‘Bitwise OR’ combines corresponding bits from two numbers, resulting in a 1 if at least one of the bits is 1.  In contrast, the ‘Bitwise Exclusive OR’ produces a 1 only when the corresponding bits are different.

Is ‘Bitwise OR’ associative?

Yes, bitwise OR(|) is associative. In other words, the result of the operation is not affected by the number of operands. Bitwise operations are associative because the operation takes place independently on each of the corresponding bits. So, for any binary number A, B, and C, you can write the following expression: A | B | C returns the same value as B | C |A or C | A | B. This property of bitwise OR makes it versatile in the sense that it can be used to combine or set individual bits across different values. The fact that the operations are grouped doesn’t affect the final result.

What is ‘Bitwise’ vs ‘Logical OR’ Operator?

The logical OR and bitwise OR are two different operators that serve different functions in programming. The bitwise OR works at the binary level. It compares the corresponding bits in the binary numbers and returns a binary value. On the other hand, the logical OR works at a higher level and is used in Boolean expressions. It evaluates to true when at least one condition is true and to false when both conditions are false.

Related Articles


<< Go Back to Bitwise Operators in Bash Scripting | Bash Operator | Bash Scripting Tutorial  

Rate this post
Mohammad Shah Miran

Hey, I'm Mohammad Shah Miran, previously worked as a VBA and Excel Content Developer at SOFTEKO, and for now working as a Linux Content Developer Executive in LinuxSimply Project. I completed my graduation from Bangladesh University of Engineering and Technology (BUET). As a part of my job, i communicate with Linux operating system, without letting the GUI to intervene and try to pass it to our audience.

Leave a Comment