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 a polymorphic compound assignment operator. Its exact behavior—string concatenation, arithmetic addition, or array appending—is dictated by the data type attribute of the target variable and the evaluation context in which the operator is invoked.

String Concatenation (Default Context)

By default, Bash treats untyped variables as strings. When applied to a standard variable outside of an arithmetic context, += appends the right-hand operand to the existing string value of the left-hand operand.
str="foo"
str+="bar" 

# Result: str="foobar"

Arithmetic Addition

To perform numeric addition, the += operator must be evaluated within an arithmetic expansion context, or the target variable must be explicitly typed with the integer attribute. Using Arithmetic Context ((( )) or let):
val=5
((val += 5))

# Result: val=10
Using the Integer Attribute (declare -i): If a variable is declared as an integer, Bash automatically forces an arithmetic evaluation context for assignments.
declare -i num=10
num+=5

# Result: num=15

Array Appending

When applied to arrays, += appends elements. The syntax requires the right-hand operand to be an array definition enclosed in parentheses (). Indexed Arrays: Appends new elements sequentially, starting at the highest existing index plus one.
declare -a arr=("a" "b")
arr+=("c" "d")

# Result: arr=("a" "b" "c" "d")
Associative Arrays: Merges new key-value pairs into the existing hash map. If a key already exists, its value is overwritten.
declare -A dict=(["key1"]="val1")
dict+=(["key2"]="val2" ["key3"]="val3")

# Result: dict contains key1, key2, and key3
Crucial Syntax Distinction for Arrays: If the parentheses are omitted on the right-hand side when targeting an array, Bash treats the operation as a string concatenation targeting the 0th index of the array, rather than appending a new element.
arr=("a" "b")
arr+="c"

# Result: arr[0] is now "ac", arr[1] remains "b"
Master Bash with Deep Grasping Methodology!Learn More