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.

An indexed array in Bash is a zero-based, one-dimensional, sparse data structure that maps integer subscripts to string values. Because Bash arrays are inherently sparse, they do not require contiguous allocation, allowing elements to be assigned to arbitrary, non-sequential indices.

Declaration

Arrays can be declared explicitly using the declare built-in with the -a option, or implicitly through assignment.

# Explicit declaration
declare -a my_array


# Implicit declaration via compound assignment
my_array=("element1" "element2")

Initialization and Assignment

Values can be assigned using compound assignment, individual subscript assignment, or by appending.

# Compound assignment (indices 0, 1, 2)
arr=("alpha" "beta" "gamma")


# Specific index assignment (creates a sparse array)
arr[10]="omega"


# Appending to an existing array
arr+=("delta" "epsilon")

Element Access via Parameter Expansion

Accessing array elements requires curly braces {} to prevent Bash from interpreting the subscript brackets as literal characters.

# Access a specific element
echo "${arr[0]}"


# Access all elements as separate words (preserves whitespace within elements)
echo "${arr[@]}"


# Access all elements as a single string (separated by the first character of IFS)
echo "${arr[*]}"

Array Metadata

Bash provides specific parameter expansion syntax to retrieve the size of the array, the length of individual elements, and the populated indices.

# Get the total number of elements in the array
echo "${#arr[@]}"


# Get the string length of a specific element
echo "${#arr[0]}"


# Get the list of allocated indices (useful for sparse arrays)
echo "${!arr[@]}"

Slicing

You can extract a subset of an array using the offset and length syntax. The offset represents the number of populated elements to skip, which does not necessarily correspond to the literal index due to the sparse nature of Bash arrays.

# Syntax: ${array_name[@]:offset:length}

# Extracts 2 elements starting from offset 1 (skips the first populated element)
slice=("${arr[@]:1:2}")

Deletion

The unset built-in is used to remove individual elements or destroy the entire array. Removing an element does not shift the indices of subsequent elements; it merely deallocates that specific subscript. Array indices passed to unset must always be quoted to prevent unintended pathname expansion (globbing).

# Delete a specific element (creates a gap in the indices)

# Quotes prevent globbing hazards (e.g., matching a file named 'arr1' in the directory)
unset 'arr[1]'


# Delete the entire array
unset arr
Master Bash with Deep Grasping Methodology!Learn More