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 AND assignment operator. It performs a bitwise AND operation between the current integer value of a variable and an evaluated expression, assigning the resulting integer back to the original variable. This operator functions exclusively within Bash arithmetic evaluation contexts. It evaluates both operands as integers (typically 64-bit signed integers, depending on the architecture), converts them to their binary representations, and applies the logical AND operation to each corresponding pair of bits. A bit in the result is set to 1 if and only if both corresponding bits in the operands are 1; otherwise, it is set to 0.

Syntax

The operator must be used within an arithmetic expansion or the let builtin:

# Using arithmetic evaluation (preferred)
(( variable &= expression ))


# Using the let builtin
let "variable &= expression"

Mechanics

The operation (( x &= y )) is functionally equivalent to the expanded expression (( x = x & y )). Evaluation Steps:
  1. The right-hand expression is evaluated to an integer.
  2. The current value of variable is evaluated to an integer.
  3. Both integers are aligned by their binary bits.
  4. The bitwise AND (&) is computed.
  5. The resulting integer is stored in variable.
Binary Evaluation Example: If a variable val is initialized to 12 and the operation (( val &= 10 )) is executed, the bitwise evaluation proceeds as follows:
  1100  (12 in decimal)
& 1010  (10 in decimal)

  1000  (8 in decimal)
After execution, the variable val holds the integer value 8.

Contextual Rules

  • Base Conversion: Bash automatically handles base conversions if the operands are prefixed appropriately (e.g., 0x for hexadecimal, 0 for octal, 2# for binary). The bitwise operation itself always occurs at the binary level, regardless of the input base.
  • Uninitialized Variables: If the target variable is uninitialized or null, Bash treats its initial value as 0 during the arithmetic evaluation. Consequently, (( uninitialized_var &= 5 )) will result in 0.
  • Non-integer Strings: If a variable contains a non-integer string, Bash attempts to evaluate the string as an arithmetic expression or variable name. If it cannot be resolved to an integer, it defaults to 0 before applying the bitwise AND.
Master Bash with Deep Grasping Methodology!Learn More