Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The |= operator in Bash is the bitwise inclusive OR assignment operator. It performs a bitwise OR operation between a variable (the left-hand side operand) and an evaluated expression (the right-hand side operand), and immediately assigns the resulting integer back to the variable.

Syntax

Because Bash variables are untyped strings by default, the |= operator must be executed within an arithmetic evaluation context.
(( variable |= expression ))
Alternatively, it can be used with the let builtin:
let "variable |= expression"

Mechanics

  1. Operand Evaluation: The right-hand side expression is fully evaluated as an integer.
  2. Bitwise OR (|): Bash converts both the current value of the variable and the evaluated right-hand side into their underlying binary representations (typically 64-bit signed integers, depending on the system architecture). It then compares them bit by bit. If a bit is 1 in either operand, the corresponding bit in the result is set to 1. It is set to 0 only if both bits are 0.
  3. Assignment (=): The final binary result is converted back to a base-10 integer and assigned to the left-hand side variable.

Equivalence

The compound assignment |= is strictly syntactic sugar for a standard bitwise OR operation followed by an assignment:
(( x |= y ))


# is functionally identical to:
(( x = x | y ))

Evaluation Example

When the operator is applied, the operation occurs at the binary level:
x=10         # Binary representation: 1010
(( x |= 6 )) # Binary representation: 0110
             # Bitwise OR result:     1110 (Decimal 14)

echo $x      # Outputs: 14

Operator Precedence

In Bash arithmetic, the |= operator shares the second-lowest precedence level with other assignment operators (such as =, +=, &=, etc.), sitting strictly above the comma operator (,), which has the lowest precedence. Assignment operators evaluate right-to-left. Consequently, the entire right-hand side expression is evaluated before the bitwise OR assignment takes place.
x=2
(( x |= 1 << 2 )) # The bitwise shift (1 << 2) evaluates to 4 first.
                  # Then, x |= 4 is executed.
                  # x becomes 6.
Master Bash with Deep Grasping Methodology!Learn More